Sort associative array into two PHP values

I have some reservation data in the array, they are already sorted by [eng], but I also want to sort by [ampm], so each group [eng] is sorted by [ampm]. Does anyone know how to do 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

                    )
+3
source share
3 answers

you can use usort: http://www.php.net/manual/en/function.usort.php

so when engthe two elements are different, you can return 1 or -1, respectively, but if they engmatch, you can compare ampmwith the return of 0, 1 or -1, respectively.

+3
source

usort(), :

<?php

function myBookingComparer($booking1, $booking2)
{
    // the logic
}

usort($bookingArray, "myBookingComparer");
+2

, -

usort($array, function ($a, $b) {
    return strcmp($a['eng'], $b['eng']);
});

Instead, you need to do something like this:

usort($array, function ($a, $b) {
    $eng = strcmp($a['eng'], $b['eng']);

    if ($eng == 0) {
        return strcmp ($a['ampm'], $b['ampm']);
    } else {
        return $eng;
    }
});
+1
source

Source: https://habr.com/ru/post/1782593/


All Articles