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

Python开发 阅读(693) 2025-05-22 更新
<?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)
  }
}


#PHP

本文标题:PHP二维数组根据某个键值大小排序
本文链接:https://www.befun.ink/detail/49.html
声明:本站信息原创或由互联网收集,未用于商业用途,如若侵权,请联系站长删除!