php中array_multisort()函数详解示例总结

1.array_multisort()这个函数可以对多个数组进行排序,排序结果是所有的数组都按第一个数组的顺序进行排列

     举例

$a1 = ['c', 'b', 'a'];
$a2 = ['b', 'c', 'a'];
$a3 = ['b', 'a', 'c'];

array_multisort($a1,$a2,$a3);
print_r($a1);print_r('
'); print_r($a2);print_r('
'); print_r($a3);print_r('
');

  结果是

Array ( [0] => a [1] => b [2] => c )
Array ( [0] => a [1] => c [2] => b )
Array ( [0] => c [1] => a [2] => b )

2.常用的(可以理解为sql中的order by)

我们现在对他们按照年龄从大到小的顺序排列,如果年龄相同就按照名字升序排序

$array = [
    ["age" => 20, "name" => "a"],
    ["age" => 21, "name" => "d"],
    ["age" => 22, "name" => "e"],
    ["age" => 20, "name" => "b"],
    ["age" => 25, "name" => "c"]
];
array_multisort(array_column($array,'age'),SORT_NUMERIC,SORT_DESC,array_column($array,'name'),SORT_STRING,SORT_ASC,$array);
print_r($array);

结果是

Array
(
    [0] => Array
        (
            [age] => 25
            [name] => c
        )

    [1] => Array
        (
            [age] => 22
            [name] => e
        )

    [2] => Array
        (
            [age] => 21
            [name] => d
        )

    [3] => Array
        (
            [age] => 20
            [name] => a
        )

    [4] => Array
        (
            [age] => 20
            [name] => b
        )

)

 

你可能感兴趣的:(PHP,php)