简体   繁体   English

PHP:如何对多维数组值进行排序

[英]PHP: How to sort multidimentional array values

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;

Same way as usual, with usort . 与通常一样,使用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. 您可以使用reset来获取它。

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). 假设$arr['fruits']中的每个数字键将仅包含一个字符串键(水果名称)来保存单个数组。 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 IMO数值索引似乎对该数据没有用,我将使用一种结构,其中水果名称是直接在fruits下的键,例如

$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进行排序以保留字符串键。

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. 可能由于某些原因您需要以其他方式使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM