php - Ordering an array by specific value -
i have original array this:
$arr=array(10,8,13,8,5,10,10,12);
and want sort become:
$arr=array(10,10,10,8,8,13,12,5);
to final result using way:
$arr=array(10,8,13,8,5,10,10,12); // remove array contain array(1) $arr_diff=array_diff(array_count_values($arr), array(1)); // remove array contain keys of $arr_diff $arr=array_diff($arr, array_keys($arr_diff)); // sort rsort($arr); ksort($arr_diff); // unshift foreach ($arr_diff $k=>$v) { while ($v > 0) { array_unshift($arr,$k); $v--; } } // print_r($arr);
my question there more simple way?
thanks.
$occurrences = array_count_values($arr); usort($arr, function ($a, $b) use ($occurrences) { // if occurrence equal (== 0), return value difference instead return ($occurrences[$b] - $occurrences[$a]) ?: ($b - $a); });
Comments
Post a Comment