我想根据值的出现次数在php中对数组进行排序。
Array(Switzerland,Switzerland,Switzerland,Switzerland,Italy,Italy,Germany,France,France,France)
像这样......
Array(Switzerland,Switzerland, Switzerland,Switzerland,France,France,France,Italy,Italy,Germany,)
答案 0 :(得分:6)
对于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
)
答案 1 :(得分:1)
<?php
$someArray = ['aa','aa','b','ccc','ccc','ccc'];
$someArray = array_count_values($someArray);
arsort($someArray);
foreach($someArray as $key => $value)
{
for ($i = 0; $i<$value; $i++) $result[] = $key;
}
print_r($result);
?>