sort associative array by two values PHP [duplicate]
i have some booking data in an array, they are already sorted by [eng], but I also want to sort by [ampm], so each group of [eng] is sorted by [ampm]. Does anybody know how to accomplish this in php?
Array
(
[xml] => Array
(
[booking] => Array
(
[0] => Array
(
[date] => 29/12/10
[eng] => ALS
[ampm] => AM
[time] => 2.00
[type] 开发者_Python百科=> S
[seq] =>2
[duration] => 0
)
[1] => Array
(
[date] => 29/12/10
[eng] => BDS
[ampm] => PM
[time] => 2.30
[type] => S
[seq] => 3
[duration] => 0
)
you can use usort: http://www.php.net/manual/en/function.usort.php
so that when eng
from the two items are different, you can return 1 or -1 accordingly, but if eng
are the same, then you can compare ampm
to return 0, 1, or -1 accordingly.
You can use usort() function where you can define a callback to do own sort comparision logic:
<?php
function myBookingComparer($booking1, $booking2)
{
// the logic
}
usort($bookingArray, "myBookingComparer");
Presumably you're doing something like
usort($array, function ($a, $b) {
return strcmp($a['eng'], $b['eng']);
});
You would need to do something like this instead:
usort($array, function ($a, $b) {
$eng = strcmp($a['eng'], $b['eng']);
if ($eng == 0) {
return strcmp ($a['ampm'], $b['ampm']);
} else {
return $eng;
}
});
精彩评论