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.

2
  • 1
    What's the logic for that order? Number of occurrences? Commented Jul 24, 2013 at 6:31
  • 1
    Looks like dups -> no dups then high -> low.. Commented Jul 24, 2013 at 6:33

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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...
Yeah, there was a typo. Already fixed. You should have seen it yourself.
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));
As I said, you have to reverse $a and $b to switch ascending/descending order.
Thanks, you are great. Just: return ( $occurrences[$b] - $occurrences[$a]) ?: ($b - $a);. Finally solved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.