我有一个PHP数组,我使用Zend_Debug将其转储到下面:
$ids = array(13) {
[0] => string(1) "7"
[1] => string(1) "8"
[2] => string(1) "2"
[3] => string(1) "7"
[4] => string(1) "8"
[5] => string(1) "4"
[6] => string(1) "7"
[7] => string(1) "3"
[8] => string(1) "7"
[9] => string(1) "8"
[10] => string(1) "3"
[11] => string(1) "7"
[12] => string(1) "4"
}
我试图获取数组中每个数字出现的次数并将其输出到数组中。
我已尝试使用array_count_values($ids)
,但它按大多数顺序输出,但我无法得到数字出现的总时间。它给了我以下输出:
array(5) {
[7] => int(5)
[8] => int(3)
[2] => int(1)
[4] => int(2)
[3] => int(2)
}
我可以从上面的数组中看到7次出现5次,但是当我遍历数组时我可以访问它!
有什么想法吗?
干杯
学家
答案 0 :(得分:4)
您可以像这样访问您想要的数据:
$ids = array( ...);
$array = array_count_values( $ids);
foreach( $array as $number => $times_number_occurred) {
echo $number . ' occurred ' . $times_number_occurred . ' times!';
}
<强>输出:强>
7 occurred 5 times!
8 occurred 3 times!
2 occurred 1 times!
4 occurred 2 times!
3 occurred 2 times!
答案 1 :(得分:1)
使用foreach
构造循环生成的数组:
$res = array_count_values($ids);
foreach( $res as $value => $count ) {
// your code here
echo "The value ".$value." appeared ".$count." times in the array";
}