0

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
    )
Community
  • 1
  • 1
NeverPhased
  • 1,546
  • 3
  • 17
  • 31

2 Answers2

1

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));
}
Yoleth
  • 1,269
  • 7
  • 15
  • Thanks makes a lot of sense but then I have lost the parent key, please see my edit! – NeverPhased Dec 13 '16 at 14:54
  • 1
    So you can use uasort to keep indexes, and to sort it from largest to smallest use return array_shift(array_values($b)) - array_shift(array_values($a)); – Yoleth Dec 13 '16 at 14:59
0

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!

Community
  • 1
  • 1
Saumya Rastogi
  • 13,159
  • 5
  • 42
  • 45