开发者

sort associative array by two values PHP [duplicate]

This question already has answers here: How do I Sort a Multidimensional Array in PHP [duplicate] (10 answers) Closed 9 years ago.

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;
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜