3

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] => S
                        [seq] =>2
                        [duration] => 0

                    )

                [1] => Array
                    (

                        [date] => 29/12/10
                        [eng] => BDS
                        [ampm] => PM
                        [time] =>       2.30
                        [type] => S
                        [seq] =>       3
                        [duration] =>       0

                    )
jim smith
  • 71
  • 1
  • 4
  • 1
    @DampeS8N: `array_multisort` works differently. – Felix Kling Dec 29 '10 at 13:21
  • See also http://stackoverflow.com/questions/3606156/sort-an-associative-array-in-php-with-multiple-condition (the question is a mess, but the accepted answer is a pointer to what you need) – John Carter Dec 29 '10 at 13:21

3 Answers3

3

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.

nonopolarity
  • 130,775
  • 117
  • 415
  • 675
2

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");
2

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;
    }
});
lonesomeday
  • 215,182
  • 48
  • 300
  • 305