Reputation: 10649
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;
Upvotes: 0
Views: 31
Reputation: 41810
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.
Upvotes: 2