显示每个数组值的实例数

时间:2014-03-19 01:15:13

标签: php array-unique

$myArray = array(2, 7, 4, 2, 5, 7, 6, 7);

$uniques = array_unique($myArray);

除了仅在数组中显示每个值一次之外,我还将如何显示(在下面的foreach循环中)每个值在数组中填充的次数。 IE旁边的'7'(数组值),我需要显示'3'(7在数组中的次数)

foreach ($uniques as $values) {
echo $values . " " /* need to display number of instances of this value right here */ ;
}

2 个答案:

答案 0 :(得分:0)

请改用array_count_values功能。

$myArray = array(2, 7, 4, 2, 5, 7, 6, 7);
$values = array_count_values($myArray);
foreach($values as $value => $count){
echo "$value ($count)<br/>";
}

答案 1 :(得分:0)

查看array_count_values

从手册中引用:

  

示例#1 array_count_values()示例

<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>
     

以上示例将输出:

Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)
相关问题