phpmultidimensional-arrayusortarray-multisort

Sort rows in a 2d array by one column while preserving original columnar relationships


My array looks like this:

Array
(
[0] => Array
    (
        [0] => 1
        [1] => 6
        [2] => 4
        [3] => 5
    )

[1] => Array
    (
        [0] => 272.05
        [1] => 63.54
        [2] => 544.79
        [3] => 190.62
    )

[2] => Array
    (
        [0] => 2011-03-06 14:08:19
        [1] => 2011-03-06 14:29:04
        [2] => 2011-03-06 14:28:39
        [3] => 2011-03-06 14:29:28
    )

)

I want to sort by $myArray[1]. I have this usort function:

function sortAmount($a, $b) { 
    return strnatcmp($a[1], $b[1]); 
}

It is called like this:

usort($myArray, "sortAmount"); 

However, the array does not change after calling usort. I want the numbers in $myArray[1] to be sorted in ascending order, and for the corresponding indexes in $myArray[0] and $myArray[2] to change with it.


Solution

  • I think you want array_multisort:

    array_multisort($a[1], $a[0], $a[2]);
    

    gives

    Array
    (
        [0] => Array
            (
                [0] => 6
                [1] => 5
                [2] => 1
                [3] => 4
            )
    
        [1] => Array
            (
                [0] => 63.54
                [1] => 190.62
                [2] => 272.05
                [3] => 544.79
            )
    
        [2] => Array
            (
                [0] => 2011-03-06 14:29:04
                [1] => 2011-03-06 14:29:28
                [2] => 2011-03-06 14:08:19
                [3] => 2011-03-06 14:28:39
            )
    
    )
    

    Apart from that, why do you use strcmp to compare numbers?