0

I have original array like this:

$arr=array(10,8,13,8,5,10,10,12);

and want to sort so finally become:

$arr=array(10,10,10,8,8,13,12,5);

To get final result i using this way:

$arr=array(10,8,13,8,5,10,10,12);

// Remove array that contain array(1)
$arr_diff=array_diff(array_count_values($arr), array(1));

// Remove array that contain keys of $arr_diff
$arr=array_diff($arr, array_keys($arr_diff));

// Sort
rsort($arr);
ksort($arr_diff);

// unshift
foreach ($arr_diff as $k=>$v)
{
    while ($v > 0)
    {
        array_unshift($arr,$k);
        $v--;
    }
}
// print_r($arr);

My question is there an another more simple way?

Thanks.

Idham Perdameian
  • 2,199
  • 24
  • 34

1 Answers1

3
$occurrences = array_count_values($arr);
usort($arr, function ($a, $b) use ($occurrences) {
    // if the occurrence is equal (== 0), return value difference instead
    return ($occurrences[$b] - $occurrences[$a]) ?: ($b - $a);
});

See Reference: all basic ways to sort arrays and data in PHP.

Community
  • 1
  • 1
deceze
  • 510,633
  • 85
  • 743
  • 889
  • Note: you may have to reverse `$a` and `$b`, depending on whether you want it ascending or descending. I always get confused with what the result will be... – deceze Jul 24 '13 at 06:40
  • Yeah, there was a typo. Already fixed. You should have seen it yourself. – deceze Jul 24 '13 at 06:46
  • Notice has gone, but final result not print_r(array(10,10,10,8,8,13,12,5)); $arr=array(10,8,13,8,5,10,10,12); $occurrences = array_count_values($arr); usort($arr, function ($a, $b) use ($occurrences) { // if the occurrence is equal (== 0), return value difference instead return ($occurrences[$a] - $occurrences[$b]) ?: ($a - $b); }); krsort($arr); print_r($arr); I need krsort() to get print_r(array(10,10,10,8,8,13,12,5)); – Idham Perdameian Jul 24 '13 at 06:50
  • As I said, you have to reverse `$a` and `$b` to switch ascending/descending order. – deceze Jul 24 '13 at 06:52
  • Thanks, you are great. Just: return ( $occurrences[$b] - $occurrences[$a]) ?: ($b - $a);. Finally solved. – Idham Perdameian Jul 24 '13 at 06:59