Search code examples
phparrayssortingmultidimensional-arrayassociative-array

Sort the rows of a 2d array by a column


I have associative array. On print_f($array_name), I got this

Array (
        [0] => Array (
            [teamid] => abc
            [distance] => 1.25
        )
        [1] => Array (
            [teamid] => xyz
            [distance] => 0.25
        )
    )

This is that array which I want to sort according to distance. eg, This should be look like this after sorting,

Array (
    [0] => Array (
        [teamid] => xyz
        [distance] => 0.25
    )
    [1] => Array (
        [teamid] => abc
        [distance] => 1.25
    )
)

If anyone know answer then please explain or suggest me link from where I can understand from beginning. Thank You.


Solution

  • Here is what you need to do.

    $a = array(array( 'teamid' => 'abc', 'distance' => 1.25 ), array( 'teamid' => 'xyz', 'distance' => 0.25 ));
    
    $distance = array();
    foreach ($a as $key => $row)
    {
        $distance[$key] = $row['distance'];
    }
    array_multisort($distance, SORT_ASC, $a);
    
    print_r($a);
    

    This outputs

    Array
    (
        [0] => Array
            (
                [teamid] => xyz
                [distance] => 0.25
            )
    
        [1] => Array
            (
                [teamid] => abc
                [distance] => 1.25
            )
    
    )
    

    source Example #3 Sorting database results

    DEMO

    Edit

    as per Mike's comment,

    here are two answers, one tells that on single array you should use usort(as Mike's answer) and array_multisort is used to compare elements from different arrays (or sub-arrays) at the same time.

    in the other answer, as Mike wants some bench marking

    usort() is more concise and doesn't require extracting a column array to feed to array_multisort(). (It also does less than array_multisort.)

    However, when I repeatedly tested it today on arrays of 20,000 and 10,000 representative data rows, usort() was 7-15x slower than array_multisort() when the column was random values of type int and the column was pre-extracted. That is as one might expect, since for every comparison you're comparing an entire php function call to optimized intrinsic code.

    more about bench marking notes, read full answer