简体   繁体   English

在PHP中对多维数组值进行排序

[英]Sorting multidimensional array values in PHP

I have the following array: 我有以下数组:

Array ( [0] => Array 
               ( [name] => Jonah 
                 [age] => 27 )
        [1] => Array 
               ( [name] => Bianca 
                 [age] => 32 )
      )

Is it possible to sort the sub-array values in [age] into some sort of order, such as lowest to highest or vice versa? 是否可以将[age]的子数组值按某种顺序排序,例如从最低到最高,反之亦然?

You can do this using usort : 您可以使用usort做到这一点:

usort($arr, function($a, $b)
{
    return $a['age'] - $b['age']; // sorts lowest to highest
});

Swap $a and $b in the function to reverse the ordering. 在函数中交换$a$b以颠倒顺序。

I think this should be possible with bool usort ( array &$array , callback $cmp_function ) 我认为使用bool usort ( array &$array , callback $cmp_function )应该是可能的

http://php.net/manual/en/function.usort.php http://php.net/manual/zh/function.usort.php

Just define a callback that sorts by the [age] key of the value. 只需定义一个按值的[age]键排序的回调即可。

This will work: 这将起作用:

$ages = array();
foreach ($array as $value) {
  $ages[] = $value;
}

array_multisort($values, SORT_ASC, $array);

Any way is good, but this is the "PHP way" : 任何方式都是好的,但这就是“ PHP方式”

array_multisort() can be used to sort several arrays at once, or a multi-dimensional array by one or more dimensions . array_multisort()可用于一次对多个数组进行排序,也可用于按一个或多个维度对多维数组进行排序。

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

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