Idham Perdameian
Idham Perdameian

Reputation: 2277

Ordering an array by specific value

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.

Upvotes: 0

Views: 57

Answers (1)

deceze
deceze

Reputation: 522042

$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.

Upvotes: 3

Related Questions