这个问题已经有了答案:
How can I sort an array by number of occurrence of its values?
4答
我想根据值的出现次数对php中的数组进行排序。
Array(Switzerland,Switzerland,Switzerland,Switzerland,Italy,Italy,Germany,France,France,France)
这样地。。。
Array(Switzerland,Switzerland, Switzerland,Switzerland,France,France,France,Italy,Italy,Germany,)
最佳答案
对于PHP7:
<?php
$couuntries = [
'Switzerland',
'Italy',
'Switzerland',
'France',
'Switzerland',
'Italy',
'Germany',
'France',
'France',
'Switzerland',
];
$counts = array_count_values($couuntries);
usort($couuntries, function($one, $second) use ($counts) {
return $counts[$second] <=> $counts[$one];
});
print_r($couuntries);
输出:
Array
(
[0] => Switzerland
[1] => Switzerland
[2] => Switzerland
[3] => Switzerland
[4] => France
[5] => France
[6] => France
[7] => Italy
[8] => Italy
[9] => Germany
)