php 二维数组自定义排序

Posted 凌雨尘

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 二维数组自定义排序相关的知识,希望对你有一定的参考价值。

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

代码:

<?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 二维数组自定义排序的主要内容,如果未能解决你的问题,请参考以下文章

php对二维数据进行排序

PHP使用自定义键将字符串数组转换为二维数组

php中二维数组排序问题方法详解

java数组自定义排序(二维数组)

java数组自定义排序(二维数组)

C 语言二级指针内存模型 ( 指针数组 | 二维数组 | 自定义二级指针 | 将 一二 模型数据拷贝到 三 模型中 并 排序 )