NeverPhased
NeverPhased

Reputation: 1566

PHP - How to sort an array by subvalue with differing keys?

I have read up on the following which shows how to sort an array by subvalue when the key is the same. PHP Sort Array By SubArray Value

I need something like the following:

function cmp_by_optionNumber($a, $b) {
return $a["$key"] - $b["$key"];
}

...

usort($array, "cmp_by_optionNumber");

However I need to sort by value when the key is different each time? What is the best way to go about this?

Array
(
[Example1] => Array
    (
        [RabbitRabbit] => 91
    )

[Example2] => Array
    (
        [DogDog] => 176
    )

[Example3] => Array
    (
        [DuckDuck] => 206
    )
)

I want sorting to be:

Array
(
[Example3] => Array
    (
        [DuckDuck] => 206
    )

[Example2] => Array
    (
        [DogDog] => 176
    )

[Example1] => Array
    (
        [RabbitRabbit] => 91
    )
)

EDIT! Using the following code erases the parent key name!

return array_shift(array_values($b)) - array_shift(array_values($a));


Array
(
[0] => Array
    (
        [DuckDuck] => 206
    )

[1] => Array
    (
        [DogDog] => 176
    )

[2] => Array
    (
        [RabbitRabbit] => 91
    )

Upvotes: 0

Views: 73

Answers (2)

Saumya Rastogi
Saumya Rastogi

Reputation: 13703

You can use PHP's usort() like this:

function compare_options($x, $y) {
  return $x["optionNumber"] - $y["optionNumber"];
}

usort($arr, "compare_options");
var_dump($arr);

In PHP 7 or greater, <=> operator can be used like this:

usort($array, function ($a, $b) {
    return $x['optionNumber'] <=> $y['optionNumber'];
});

Hope this helps!

Upvotes: 0

Yoleth
Yoleth

Reputation: 1272

You can get the first element of an array using

$first = array_shift(array_values($array)); 

So you'll get something like this :

function cmp_by_optionNumber($a, $b) {
    return array_shift(array_values($a)) - array_shift(array_values($b));
}

Upvotes: 1

Related Questions