根据PHP中的3个键(日,月,年)对多维数组进行排序

时间:2016-11-05 12:43:11

标签: php arrays sorting multidimensional-array

我有一个像这样的多维数组(每个$ orders [$ userid]数组都有多个订单数组)

foreach($orders[$userid] as $order){
    print_r($order);
}

这是按日期,月份,年份分组的第一个用户订单

Array ( [id] => 409079 [user_id] => 26017 [total] => 30 [final_total] => 29.1 [order_status_id] => 1 
[day] => 1 [month] => 11 [year] => 2016 [amount2] => 2198.2999696731567 )

Array ( [id] => 410744 [user_id] => 26017 [total] => 175 [final_total] => 165 [order_status_id] => 1 
[day] => 2 [month] => 11 [year] => 2016 [amount2] => 2619.799982070923 )

Array ( [id] => 412268 [user_id] => 26017 [total] => 300 [final_total] => 293 [order_status_id] => 1 
[day] => 3 [month] => 11 [year] => 2016 [amount2] => 4413.400000572205 )

Array ( [id] => 405860 [user_id] => 26017 [total] => 10 [final_total] => 9.8 [order_status_id] => 1 
[day] => 30 [month] => 10 [year] => 2016 [amount2] => 352.5999994277954 )

Array ( [id] => 407500 [user_id] => 26017 [total] => 85 [final_total] => 84.5 [order_status_id] => 1 
[day] => 31 [month] => 10 [year] => 2016 [amount2] => 1135.1000022888184 )

如您所见,旧日期显示在最近日期之后。问题是如何对这个多维数组进行排序,以显示旧日期,然后显示像这样的最近日期

Array ( [id] => 405860 [user_id] => 26017 [total] => 10 [final_total] => 9.8 [order_status_id] => 1 
[day] => 30 [month] => 10 [year] => 2016 [amount2] => 352.5999994277954 )

Array ( [id] => 407500 [user_id] => 26017 [total] => 85 [final_total] => 84.5 [order_status_id] => 1 
[day] => 31 [month] => 10 [year] => 2016 [amount2] => 1135.1000022888184 )

Array ( [id] => 409079 [user_id] => 26017 [total] => 30 [final_total] => 29.1 [order_status_id] => 1 
[day] => 1 [month] => 11 [year] => 2016 [amount2] => 2198.2999696731567 )

Array ( [id] => 410744 [user_id] => 26017 [total] => 175 [final_total] => 165 [order_status_id] => 1 
[day] => 2 [month] => 11 [year] => 2016 [amount2] => 2619.799982070923 )

Array ( [id] => 412268 [user_id] => 26017 [total] => 300 [final_total] => 293 [order_status_id] => 1 
[day] => 3 [month] => 11 [year] => 2016 [amount2] => 4413.400000572205 )

2 个答案:

答案 0 :(得分:0)

请使用代码:

foreach ($orders as $key => $row) {
    $year[$key]  = $row['year'];
    $month[$key] = $row['month'];
    $day[$key] = $row['day'];
}

array_multisort($year, SORT_ASC, $month, SORT_ASC, $day, SORT_ASC, $orders);

答案 1 :(得分:0)

在更复杂的情况下,您可以使用array_multisort,在这种情况下,您可以将问题减少为仅按一个值排序。该 'year''month''day'基本上是部分日期。使用usort功能,您可以执行以下操作:

$dateToTimestamp = function (array $order) {
    $day = $order['day'];
    $month = $order['month'];
    $year = $order['year'];

    return strtotime("$day-$month-$year");
};

usort($array, function ($a, $b) use ($dateToTimestamp) {
    return $dateToTimestamp($a) - $dateToTimestamp($b);
});

使用strtotime注意的一件事是,您无法真正设置区域设置以识别字符串的哪个部分是日,月或年。在PHP手册评论之一中,有一个技巧可以弥补这一点。在我们的例子中,使用破折号分隔符确保订单。

这是working demo