如何计算数组中具有相同名称的数字键

对于平面文件博客系统,我txt在目录中有一些文件data/articles。一个 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)


慕神8447489
浏览 108回答 1
1回答

杨__羊羊

可能您的项目$lines有换行符。这意味着它club与 不一样club\n。FILE_IGNORE_NEW_LINES当您显式使用file()或修剪值时使用:$lines = file($file, FILE_IGNORE_NEW_LINES); // all lines of file in array WITHOUT linebreaks至于你的第二个问题 -array_count_values会给你新的数组,其中包含每个元素的数量:$counts = array_count_values($cat_lines);
打开App,查看更多内容
随时随地看视频慕课网APP