-3

我有一个 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 次,但是当我循环遍历数组时我可以访问它!

有什么想法吗?

干杯

J。

4

2 回答 2

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!

演示

于 2012-06-04T13:05:52.010 回答
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";
}
于 2012-06-04T13:05:58.613 回答