PHP二维数组根据某个键值大小排序

作者:IT技术圈子 浏览量:265   更新于 2023-09-30 23:51 标签:
<?php
// 原始数据结构
$data = [
    [
        'id' => 1,
        'name' => 'test1',
        'score' => 89,
    ],
    [
        'id' => 2,
        'name' => 'test2',
        'score' => 99,
    ],
    [
        'id' => 3,
        'name' => 'test3',
        'score' => 80,
    ],
    [
        'id' => 4,
        'name' => 'test4',
        'score' => 70,
    ] 
];

// 主要用到array_multisort和array_column函数,这里根据score字段按高到低排序
array_multisort(array_column($data, 'score'), SORT_DESC, $data);

var_dump($data);

?>

排序后的结果如下

array(4) {
  [0]=>
  array(3) {
    ["id"]=>
    int(2)
    ["name"]=>
    string(5) "test2"
    ["score"]=>
    int(99)
  }
  [1]=>
  array(3) {
    ["id"]=>
    int(1)
    ["name"]=>
    string(5) "test1"
    ["score"]=>
    int(89)
  }
  [2]=>
  array(3) {
    ["id"]=>
    int(3)
    ["name"]=>
    string(5) "test3"
    ["score"]=>
    int(80)
  }
  [3]=>
  array(3) {
    ["id"]=>
    int(4)
    ["name"]=>
    string(5) "test4"
    ["score"]=>
    int(70)
  }
}