IT源码网

php 二维数组自定义排序讲解

developer 2021年05月16日 编程语言 140 0

eg1:只根据一个规则进行排序,比如我下面的数组是一组满减折扣的信息,我要按照满减的金额从小到大排序

代码:

<?php 
 
$arr =[ 
    ["amount"=> 60,"discount"=> 35], 
    ["amount"=> 20,"discount"=> 10], 
    ["amount"=> 5,"discount"=> 3] 
]; 
 
$column = array_column($arr,'amount'); array_multisort($column,SORT_ASC,$arr); print_r($column); print_r($arr); ?>

输出:

Array 
( 
    [0] => 5 
    [1] => 20 
    [2] => 60 
) 
Array 
( 
    [0] => Array 
        ( 
            [amount] => 5 
            [discount] => 3 
        ) 
 
    [1] => Array 
        ( 
            [amount] => 20 
            [discount] => 10 
        ) 
 
    [2] => Array 
        ( 
            [amount] => 60 
            [discount] => 35 
        ) 
 
)

eg2:有时候需要对一个二维数组进行排序,自定义对应的排序规则,比如对一个班级里面的同学,先按身高降序排序,身高相同的,再按体重降序排序。。。

代码:

<?php 
$array = [ 
    ["id" => "1", "name" => "a", "age" => "19",], 
    ["id" => "2", "name" => "b", "age" => "39",], 
    ["id" => "3", "name" => "c", "age" => "9",], 
    ["id" => "4", "name" => "d", "age" => "1",], 
    ["id" => "5", "name" => "e", "age" => "88",], 
    ["id" => "6", "name" => "f", "age" => "65",], 
    ["id" => "7", "name" => "g", "age" => "19",], 
]; 
 
array_multisort(array_column($array,"age"),SORT_DESC,array_column($array,"id"),SORT_DESC,$array); 
print_r($array); 
?>

上面这个二维数组,先按年龄(age)降序排序,如果年龄(age)相同的话,再按 id 降序排序

输出:

Array 
( 
    [0] => Array 
        ( 
            [id] => 5 
            [name] => e 
            [age] => 88 
        ) 
 
    [1] => Array 
        ( 
            [id] => 6 
            [name] => f 
            [age] => 65 
        ) 
 
    [2] => Array 
        ( 
            [id] => 2 
            [name] => b 
            [age] => 39 
        ) 
 
    [3] => Array 
        ( 
            [id] => 7 
            [name] => g 
            [age] => 19 
        ) 
 
    [4] => Array 
        ( 
            [id] => 1 
            [name] => a 
            [age] => 19 
        ) 
 
    [5] => Array 
        ( 
            [id] => 3 
            [name] => c 
            [age] => 9 
        ) 
 
    [6] => Array 
        ( 
            [id] => 4 
            [name] => d 
            [age] => 1 
        ) 
 
)

如果遇到下面的PHP警告,就是你拿来比较的标志的数组大小跟待排序的数组大小不一致,可以把 array_multisort 里面的数组都打印出来看下大小是否一致

PS:PHP Warning : array_multisort(): Array sizes are inconsistent


发布评论

分享到:

IT源码网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

建行互联网银企被扫支付讲解
你是第一个吃螃蟹的人
发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。