将数组计数值的结果排序到新数组中

时间:2014-02-18 08:04:31

标签: php arrays sorting count duplicates

我想将结果排序到一个新数组但没有$ key 因此,最独特的数字将是第一个(或者最重复的数字将是第一个)。

<?php

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

foreach (array_count_values($a) as $key => $value) {
        echo $key.' - '.$value.'<br>'; 
}

//I am expecting to get the most duplicated number FIRST (without the $key)
//so in that case :
// $newarray = array(4,3,2,1,5); 
?>

3 个答案:

答案 0 :(得分:1)

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

$totals = array_count_values($a);

arsort( $totals );

echo "<pre>";
print_r($totals);

输出

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

答案 1 :(得分:1)

这样做

<?php
$a = array (1,1,2,2,2,3,3,3,3,4,4,4,4,4,5,6,7,8,9);
$n=array_count_values($a);
arsort($n);
print_r(array_keys($n));

Demo

<强>输出

   Array
(
    [0] => 4
    [1] => 3
    [2] => 2
    [3] => 1
    [4] => 9
    [5] => 8
    [6] => 5
    [7] => 6
    [8] => 7
)

答案 2 :(得分:0)

$newarray = array_keys(array_count_values($a));