Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a three dimensional array and I want to sort the arrays in the first dimension on a value in the third dimension. Like the following:

Array
(
[0] => Array
    (
        [0] => Array
            (
                [data] => 7
                [field] => 1
                [type] => string
            )

        [1] => Array
            (
                [data] => 2011/07/13
                [field] => -2
                [sort] => 1310594015
            )

        [2] => Array
            (
                [data] => admin
                [field] => -1
                [sort] => admin
            )
    )

[1] => Array
    (
        [0] => Array
            (
                [data] => 6
                [field] => 1
                [type] => string
            )

        [1] => Array
            (
                [data] => 2011/07/14
                [field] => -2
                [sort] => 1310667194
            )

        [2] => Array
            (
                [data] => admin
                [field] => -1
                [sort] => admin
            )
    )
)

I would like to sort the arrays at the first level (i.e. there are only 2 of them) based on the value of the 'data' key, down in the third level. In this case, the two arrays at the first level should swap so the array with the value of 6 for 'data' comes before the one with 7. The array that contains the 'data' key will always be at position [0] of the second level.

share|improve this question
add comment (requires an account with 50 reputation)

1 Answer

up vote 4 down vote accepted
usort($allArray,function($a,$b){
     return $a[0]['data']-$b[0]['data'];
})
share|improve this answer
+1. Elegant solution. Believe it requires PHP 5.3. – Frank Farmer Jul 14 '11 at 19:07
@FrankFarmer, yes it is requires PHP 5.3+. But It is easy to rewrite it to 5.2- with create_function/dummy function – RiaD Jul 14 '11 at 19:10
Fantastic, works perfectly. Thanks. – Dan Grec Jul 14 '11 at 19:18
@Dan Grec. You can tick messages which are solution for your answers ;) – RiaD Jul 14 '11 at 19:20
Thanks. I tried to up vote it, and gave up when it wouldn't let me do that :) – Dan Grec Jul 14 '11 at 19:30
add comment (requires an account with 50 reputation)

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.