在多维数组中按键排序

时间:2018-02-12 05:07:24

标签: php arrays sorting

Array
(
    [0] => Array
        (
            [sales] => 117513.00000000
            [month] => 1
            [month_name] => January
            [year] => 2018
        )

    [1] => Array
        (
            [purchases] => 136350.00000000
            [month] => 9
            [month_name] => September
            [year] => 2017
        )

    [2] => Array
        (
            [sales] => 23025.00000000
            [month] => 11
            [month_name] => November
            [year] => 2017
        )

    [3] => Array
        (
            [sales] => 6447.00000000
            [month] => 12
            [month_name] => December
            [year] => 2017
        )

)

在这里,我已经逐年对数组进行了排序,但我需要按月降序排序。

Array
(

 [0] => Array
        (
            [sales] => 117513.00000000
            [month] => 1
            [month_name] => January
            [year] => 2018
        )

    [1] => Array
        (
            [purchases] => 6447.00000000
            [month] => 12
            [month_name] => December
            [year] => 2017
        )

    [2] => Array
        (
            [sales] => 23025.00000000
            [month] => 11
            [month_name] => November
            [year] => 2017
        )

    [3] => Array
        (
            [sales] => 136350.00000000
            [month] => 9
            [month_name] => September
            [year] => 2017
        )

)

如何获取第二种格式,按月分类..

1 个答案:

答案 0 :(得分:0)

使用array_multisort函数执行此操作。

<?php

// Obtain a list of columns
foreach ($data as $key => $row) {
  $month[$key]  = $row['month'];
}


array_multisort($month, SORT_DESC);
?>