phpsortingasort

asort using the second element


Starting with this array :

$TEST=array (
    0 => array ( 0 => 'b', 1 => 'y', 2 => 'O', ),
    1 => array ( 0 => 'a', 1 => 'z', 2 => 'O', ),
    2 => array ( 0 => 'c', 1 => 'x', 2 => 'O', ),
)

How to sort it to have ? (xyz based on second element) :

$TEST=array (
    2 => array ( 0 => 'c', 1 => 'x', 2 => 'O', ),
    0 => array ( 0 => 'b', 1 => 'y', 2 => 'O', ),
    1 => array ( 0 => 'a', 1 => 'z', 2 => 'O', ),
)

The result of a simple asort($TEST) is (abc based on first element) :

$TEST=array (
    1 => array ( 0 => 'a', 1 => 'z', 2 => 'O', ),
    0 => array ( 0 => 'b', 1 => 'y', 2 => 'O', ),
    2 => array ( 0 => 'c', 1 => 'x', 2 => 'O', ),
)

Solution

  • You can do that with this one line of code:

    array_multisort( array_column($yourArray, $index), SORT_ASC, $yourArray );
    

    In your case, this is how to use it:

    $TEST=array (
        0 => array ( 0 => 'b', 1 => 'y', 2 => 'O', ),
        1 => array ( 0 => 'a', 1 => 'z', 2 => 'O', ),
        2 => array ( 0 => 'c', 1 => 'x', 2 => 'O', ),
    )
    array_multisort( array_column($TEST, 1), SORT_ASC, $TEST );
    print_r($TEST);
    

    Check array_multisort here http://php.net/manual/en/function.array-multisort.php