猿问

如何从旧数组中按每个重复值的计数降序创建新数组

我想从一个旧数组中安排一个新数组,其中有多个值,其中也有重复值(在旧数组中)。


所需的编码应如下所示


like so


$old_array = array("1", "2" ,"3", "1", "5", "2", "2", "3", "3", "3", "6");


$new_array = array("3","2","1","5","6"); 

新数组按值频率的降序排列。例如。“3”的计数为 4,“2”的计数为 3,“1”的计数为 2,依此类推


偶然的你
浏览 92回答 2
2回答

MM们

$old_array = array("1", "2" ,"3", "1", "5", "2", "2", "3", "3", "3", "6");          $values = array_count_values( $old_array );             arsort($values);            $result = array_keys($values);输出(对于 php 5.6.35):$result =     array(    (int) 0 => (int) 3,    (int) 1 => (int) 2,    (int) 2 => (int) 1,    (int) 3 => (int) 6,    (int) 4 => (int) 5)

千万里不及你

一种选择是使用array_count_values,然后使用uksort根据原始数组中的值对键进行排序。排序后,取array_keys。$old_array = array("1", "2" ,"3", "1", "5", "2", "2", "3", "3", "3", "6");$result = array_count_values($old_array);uksort($result, function($a, $b) use ($result){&nbsp; &nbsp; return $result[$a] < $result[$b];});$new_array = array_keys($result);print_r($new_array);输出Array(&nbsp; &nbsp; [0] => 3&nbsp; &nbsp; [1] => 2&nbsp; &nbsp; [2] => 1&nbsp; &nbsp; [3] => 5&nbsp; &nbsp; [4] => 6)
随时随地看视频慕课网APP
我要回答