在php中排序并显示数组

时间:2011-10-13 18:12:54

标签: php arrays

好的,我有这个:

array(2, 2, 2, 2, 2, 3, 4, 2, 1, 2, 5, 5, 68);

我希望输出:

There exists 6 x 2s in the array
1 x 3
1 x 4
2 x 5
1 x 68

我该怎么做?

2 个答案:

答案 0 :(得分:1)

查看array_count_values()功能。

Example

$arr = array(2, 2, 2, 2, 2, 3, 4, 2, 1, 2, 5, 5, 68);

foreach(array_count_values($arr) as $value => $count)
{
    printf("%d x %d<br />\n", $count, $value);
}

答案 1 :(得分:1)

答案是array_count_values

$array = array(2, 2, 2, 2, 2, 3, 4, 2, 1, 2, 5, 5, 68);
print_r(array_count_values($array))

查看documentation

输出

Array
(
    [2] => 6
    [3] => 1
    [4] => 1
    [5] => 2
    [68] => 1
)