phparrayssorting

How to sort all rows of a 2d array to mirror the sort of the first row?


I have an array as below:

Array
(
    [time] => Array
        (
            [0] => 6:00 PM
            [1] => 4:00 PM
        )

[id] => Array
    (
        [0] => #1 Hits of the 60's
        [1] => 3 Men and a Lady
    )

[url] => Array
    (
        [0] => hits-of-the-60
        [1] => 3-men-and-a-lady
    )

[ev_evc_id] => Array
    (
        [0] => 2
        [1] => 2
    )

[address] => Array
    (
        [0] => Caravelle Theatre
        [1] => God and Country Theatre
    )

[phone] => Array
    (
        [0] => 1-800-4Branson (800-427-2676)
        [1] => 1-800-4Branson (800-427-2676)
    )

)

I want to sort the array based on time ascending.

Desired output is as below:

Array
(
    [time] => Array
        (
            [0] => 4:00 PM
            [1] => 6:00 PM
        )
[id] => Array
    (
        [0] => 3 Men and a Lady
        [1] => #1 Hits of the 60's
    )

[url] => Array
    (
        [0] => 3-men-and-a-lady
        [1] => hits-of-the-60
    )

[ev_evc_id] => Array
    (
        [0] => 2
        [1] => 2
    )

[address] => Array
    (
        [0] => God and Country Theatre
        [1] => Caravelle Theatre
    )

[phone] => Array
    (
        [0] => 1-800-4Branson (800-427-2676)
        [1] => 1-800-4Branson (800-427-2676)
    )

)

I have tried asort, usort. But could not make it work.


Solution

  • You can do it with array_multisort, it will sort all arrays based on the first array given:

    array_multisort(
        $myArray["time"],
        $myArray["id"],
        $myArray["url"],
        $myArray["ev_evc_id"],
        $myArray["address"],
        $myArray["phone"]
    );