【问题标题】:Sort array in ASC order depending on two key values?根据两个键值按 ASC 顺序对数组进行排序?
【发布时间】:2018-01-17 04:45:19
【问题描述】:

我有一个存储在一个变量中的数组。数组如下:

Array
(
[0] => Array
    (
        [employee_name] => Amit
        [today_date] => 2018-01-11
    )

[1] => Array
    (
        [employee_name] => Amit
        [today_date] => 2018-01-09
    )

[2] => Array
    (
        [employee_name] => Amit
        [today_date] => 2018-01-10
    )
[3] => Array
    (
        [employee_name] => GURVINDER
        [today_date] => 2018-01-11
    )

[4] => Array
    (
        [employee_name] => GURVINDER
        [today_date] => 2018-01-10
    )
)

我已经完成了使用employee_name 对数组进行升序排序,这段代码运行得很好:

$attendances = "above array";
uasort($attendances, function($a, $b) {
     return strcmp($a["employee_name"], $b["employee_name"]);
 }); // this code is sorting in ascending order with employee_name.

现在我想要的是每个employee_name 应该是升序,每个employee_name today_date 也应该是升序。我的预期输出是这样的:

Array
(
[0] => Array
    (
        [employee_name] => Amit
        [today_date] => 2018-01-09
    )

[1] => Array
    (
        [employee_name] => Amit
        [today_date] => 2018-01-10
    )

[2] => Array
    (
        [employee_name] => Amit
        [today_date] => 2018-01-11
    )
[3] => Array
    (
        [employee_name] => GURVINDER
        [today_date] => 2018-01-10
    )

[4] => Array
    (
        [employee_name] => GURVINDER
        [today_date] => 2018-01-11
    )
)

请帮我解决这个问题。由于某些原因,我不会使用 SQL 查询。提前致谢。

【问题讨论】:

    标签: php arrays sorting


    【解决方案1】:

    根据您的输出要求,这可以正常工作。试试这个:

    array_multisort(array_column($attendances, 'employee_name'),  SORT_ASC,
                array_column($attendances, 'today_date'), SORT_ASC,
                $attendances);
    echo "<pre>";
    print_r($attendances);
    

    输出:-https://eval.in/935967

    【讨论】:

    • 是的,这是正确的。+1。为什么这不是我的想法,因为我已经多次使用它:):)
    猜你喜欢
    • 1970-01-01
    • 2021-06-05
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 2013-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多