I have the following array:
$data =
[
[
'totals' => ['grand_total' => 729.81, 'lowest_order_date' => '', 'lowest_created_at' => '2022-11-23 15:23:06'],
],
[
'totals' => ['grand_total' => 746.03, 'lowest_order_date' => '', 'lowest_created_at' => '2022-11-22 19:46:13'],
],
[
'totals' => ['grand_total' => 729.81, 'lowest_order_date' => '2022-11-22 15:30:22', 'lowest_created_at' => '2022-11-21 14:25:07'],
],
];
And I'm using the following code to sort it:
usort($data, function ($a, $b)
{
return
($a['totals']['grand_total'] <=> $b['totals']['grand_total']) +
($a['totals']['lowest_order_date'] <=> $b['totals']['lowest_order_date']) +
($a['totals']['lowest_created_at'] <=> $b['totals']['lowest_created_at']);
});
I was expecting this function to sort the content by the following priority:
- Grand total <-- The main priority ASC
- Lowest order date <-- If grand total equal, check this
- Lowest created at <-- If grand total equal, check this
However, the output puts the 746.03 as first result:
$data =
[
[
'totals' => ['grand_total' => 746.03, 'lowest_order_date' => '', 'lowest_created_at' => '2022-11-22 19:46:13'],
],
[
'totals' => ['grand_total' => 729.81, 'lowest_order_date' => '', 'lowest_created_at' => '2022-11-23 15:23:06'],
],
[
'totals' => ['grand_total' => 729.81, 'lowest_order_date' => '2022-11-08 15:30:22', 'lowest_created_at' => '2022-11-21 14:25:07'],
],
];
Expected output:
$data =
[
[
'totals' => ['grand_total' => 729.81, 'lowest_order_date' => '', 'lowest_created_at' => '2022-11-23 15:23:06'],
],
[
'totals' => ['grand_total' => 729.81, 'lowest_order_date' => '2022-11-22 15:30:22', 'lowest_created_at' => '2022-11-21 14:25:07'],
],
[
'totals' => ['grand_total' => 746.03, 'lowest_order_date' => '', 'lowest_created_at' => '2022-11-22 19:46:13'],
],
];
By looking at the problem, it seems to me logical that I first need to sort only by grand_total and then perform sort on lowest_order_date & lowest_created_at if the grand_total is equal. Is there an easy way to do it by using the sort functions?