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
    )

2 Answers 2

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));
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks makes a lot of sense but then I have lost the parent key, please see my edit!
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));
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!

Comments

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.