0

I'm totally desperate.
How can I sort an array in 3rd level that has an ID in the second level?
I want to sort this array only for "cars" and then ascending by "age"

array (   
    ['cars'] => array (
        [23] => array(
            ['age'] => 10,
            ['color'] => 'yellow',
        ),
        [16] => array(
            ['age'] => 12,
            ['color'] => 'purple'
        ),
        [45] => array(
            ['age'] => 3,
            ['color'] => 'silver'
        )
    ),
    ['pages'] => array (
        [0] => array (
            ['number'] => 2
        )
    )
)
1
  • Try PHPs built-in function uasort() Commented Sep 30, 2014 at 8:50

2 Answers 2

2

You can use uasort.

uasort($a['cars'], function($a, $b) {
   return $a['age'] > $b['age'] ? 1 : -1;
});

https://eval.in/200162

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

2 Comments

@Tipo That's it. Have a look at the eval link
actually no need for a ternary on the return, $a['age'] - $b['age'] is okay on integers
0

If you just want to sort the array values and don't care for the keys, use sort(). This will give a new array with numeric keys starting from 0.

If you want to keep the key-value associations, use uasort().

check this comparison table of sorting functions in PHP.

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.