php 二维数组排序从大到小
时间: 2023-08-18 21:38:59 浏览: 245
可以使用PHP中的`usort()`函数来实现二维数组按照指定键的值从大到小排序。
示例代码:
```
$students = array(
array('name' => 'Tom', 'age' => 18, 'score' => 90),
array('name' => 'John', 'age' => 20, 'score' => 85),
array('name' => 'Mary', 'age' => 19, 'score' => 95),
array('name' => 'Peter', 'age' => 21, 'score' => 80)
);
usort($students, function($a, $b) {
return $b['score'] - $a['score'];
});
print_r($students);
```
输出结果:
```
Array
(
[0] => Array
(
[name] => Mary
[age] => 19
[score] => 95
)
[1] => Array
(
[name] => Tom
[age] => 18
[score] => 90
)
[2] => Array
(
[name] => John
[age] => 20
[score] => 85
)
[3] => Array
(
[name] => Peter
[age] => 21
[score] => 80
)
)
```
在上面的示例代码中,我们定义了一个包含四个学生信息的二维数组。然后使用`usort()`函数来对数组进行排序,传入一个匿名函数用于指定排序规则,这里我们按照`score`字段的值从大到小进行排序。最后,我们使用`print_r()`函数输出排序后的数组。
阅读全文