简体   繁体   中英

How to sort associative array?

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.

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

$array = array(
    array('teamid' => 'a', 'distance' => 1.25),
    array('teamid' => 'b', 'distance' => 0.25),
    array('teamid' => 'c', 'distance' => 2.5),
    array('teamid' => 'd', 'distance' => 0.75),
);


function cmp($a, $b)
{
    if ($a['distance'] == $b['distance']) return 0;
    return ($a['distance'] < $b['distance']) ? -1 : 1;
}

usort($array, "cmp");

More info: http://php.net/usort

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM