phparrayssortingmultidimensional-array

Sort the rows of a 2D array by a column


how to sort this kind of array? this will be sort by array[x][1]. can this be sorted using usort?

Array
(
    [0] => Array
        (
            [0] => 1247
            [1] => 3
            [2] => no
            [3] => no
        )

    [1] => Array
        (
            [0] => 224
            [1] => 1
            [2] => no
            [3] => no
        )

    [2] => Array
        (
            [0] => 226
            [1] => 2
            [2] => no
            [3] => no
        )

)

Solution

  • You're on the right track with usort(), you simply need to compare against the 2nd element in the array (as you required).

    usort($array, function($i, $v) {
        return $i[1] - $v[1];
    });
    

    Note: The above $array is your array that you want to sort.

    Which will return it in the correct order (1,2 then 3).

    Example/Demo