【问题标题】:How to count number keys in array which have the same name如何计算数组中具有相同名称的数字键
【发布时间】:2020-08-23 21:19:57
【问题描述】:

对于平面文件博客系统,我在目录data/articles 中有一些txt 文件。 txt 文件如下所示:

id_20200430223049                    // id
Friends                              // category
uploads/mainimage_5eab357970b0d.jpeg // image
Officials wanted                     // title
comment<br />comment<br />comment    // comment

如何计算所有 txt 文件中每个类别的类别数?

可以说:我有 6 个文本文件。在每个文件的第 2 行:

其中 2 个属于 俱乐部

其中 2 个属于 同事

1 有类别家庭

并且 1 具有类别朋友

到目前为止我有什么:

$files = glob("data/articles/*.txt"); // Specify the file directory by extension (.txt)
$cat_lines = array();
foreach($files as $file) {

        $lines = file($file); // all lines of file in array
        $cat_lines[] = strtolower($lines[1]); // grab the category lines and put in array

}

print_r($cat_lines); 给了我这个输出:

Array ( [0] => friends [1] => family [2] => club [3] => colleagues [4] => club [5] => colleagues )

要计算我使用的数组中键的数量:

echo count (array_keys( $cat_lines, strtolower("Club") ) );

不幸的是,它给了我 0 作为输出而不是 2 !!!我不明白这个...

但除此之外,我最终想要实现的是:我如何创建一个 foreach 循环来给我这样的输出:

Friends (1)
Family (1)
Club (2)
Colleagues (2)

【问题讨论】:

    标签: php arrays foreach count array-key


    【解决方案1】:

    $lines 中的项目可能有换行符。这意味着clubclub\n 不同。

    当您使用file() 或显式修剪值时使用FILE_IGNORE_NEW_LINES

    $lines = file($file, FILE_IGNORE_NEW_LINES); // all lines of file in array WITHOUT linebreaks
    

    至于您的第二个问题 - array_count_values 将为您提供包含其中每个元素计数的新数组:

    $counts = array_count_values($cat_lines);
    

    【讨论】:

    • FILE_IGNORE_NEW_LINES 现在给了我 2。超级解决方案!我同意,新数组counts 正是我们要找的地方。感谢这个解决方案!
    猜你喜欢
    • 2019-09-02
    • 2021-11-24
    • 2020-11-03
    • 2015-08-18
    • 2014-11-19
    • 1970-01-01
    • 2021-05-26
    • 2021-03-20
    • 1970-01-01
    相关资源
    最近更新 更多