0

I am trying to sort a multidimensional array by priority:

$arr['fruits'][0]['banana']['color'] = 'yellow';
$arr['fruits'][0]['banana']['qty'] = '50';
$arr['fruits'][0]['banana']['priority'] = 3;

$arr['fruits'][1]['apple']['color'] = 'red';
$arr['fruits'][1]['apple']['qty'] = '75';
$arr['fruits'][1]['apple']['priority'] = 1;

$arr['fruits'][2]['grape']['color'] = 'purple';
$arr['fruits'][2]['grape']['qty'] = '100';
$arr['fruits'][2]['grape']['priority'] = 5;

How do I sort this array in order to get the values sorted by priority?

$arr['fruits'][0]['apple']['color'] = 'red';
$arr['fruits'][0]['apple']['qty'] = 75;

$arr['fruits'][1]['banana']['color'] = 'yellow';
$arr['fruits'][1]['banana']['qty'] = 50;

$arr['fruits'][2]['grape']['color'] = 'purple';
$arr['fruits'][2]['grape']['qty'] = 100;
2
  • 1
    What have you tried? Attach your code. Commented Apr 13, 2018 at 22:32
  • Possible duplicate of Sort Multi-dimensional Array by Value Commented Apr 13, 2018 at 22:39

1 Answer 1

2

Same way as usual, with usort. The trick for this specific one is that the things you're sorting have one extra array level inside with a string key that you won't know in advance. You can get it using reset though.

usort($arr['fruits'], function($a, $b) {
    return reset($a)['priority'] <=> reset($b)['priority'];
});

This is assuming that each of the numeric keys in $arr['fruits'] will hold a single array with only one string key (the name of the fruit). IMO the numeric index doesn't seem useful for this data, and I would use a structure where the fruit name is the key directly under fruits, like

$arr['fruits'] = [
    'banana' => ['color' => 'yellow', 'qty' => '50',  'priority' => 3],
    'apple' =>  ['color' => 'red',    'qty' => '75',  'priority' => 1],
    'grape' =>  ['color' => 'purple', 'qty' => '100', 'priority' => 5],
];

which you could sort with uasort to preserve the string keys.

uasort($arr['fruits'], function($a, $b) {
    return $a['priority'] <=> $b['priority'];
});

But I don't know the whole picture; there may be some reason you need to have it the other way.

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

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.