【发布时间】: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