multi dimensional array sorting by string

Itai Sagi picture Itai Sagi · Nov 1, 2011 · Viewed 10.7k times · Source

I'm breaking my head trying to figure out how to do this right, I have this multi dimensional array:

Array
(
    [0] => Array
        (
            [time] => November 1st 10:10
            [query] => movies
            [set] => 1
            [matches] => No matching results
            [results] => 5
        )

    [1] => Array
        (
            [time] => November 1st 10:10
            [query] => cinemas
            [set] => 1
            [matches] => No matching results
            [results] => 2
        )

)

In real life, there could be alot more sub-arrays, but et's say I want to sort it by "query" alphabetically, how can I achieve this?

I saw only solutions for integer type or key index, the end result, in this case, would be:

Array
    (
        [0] => Array
            (
                [time] => November 1st 10:10
                [query] => cinemas
                [set] => 1
                [matches] => No matching results
                [results] => 2
            )
        [1] => Array
            (
                [time] => November 1st 10:10
                [query] => movies
                [set] => 1
                [matches] => No matching results
                [results] => 5
            )

    )

Much appreciated, thanks.

Answer

Hammerite picture Hammerite · Nov 1, 2011
function querySort ($x, $y) {
    return strcasecmp($x['query'], $y['query']);
}

usort($myArray, 'querySort');