CrabLab
CrabLab

Reputation: 182

PHP sorting a set of multidimensional arrays

I have an array which contains another array with a distance and ID in it. I need to sort the distance part of the array, so the ID remains correlated with it's respective distance.

Eg.

array
(
    [0] => array(
                    [0] => 170
                    [1] => 123abc
    )
    [1] => array(
                    [0] => 150
                    [1] => 456def
    )
) 

Now, I want to sort the distances ascending so my sorted output would look like:

array
(
    [0] => array(
                    [0] => 150
                    [1] => 456def
    )
    [1] => array(
                    [0] => 170
                    [1] => 123abc
    )
) 

As 150 is smaller than 170, it has 'moved' up.

I've looked at the PHP functions for this; array_multisort() etc. however these only seem to sort the values within the arrays rather than a set of arrays.

Any help appreciated.


EDIT: There isn't a fixed number of items within the first array - it ranges from 1 to infinity.

Upvotes: 1

Views: 49

Answers (1)

roullie
roullie

Reputation: 2820

use usort

usort($yourArray, function($a, $b) {
    return $a[0] - $b[0]; // index 0 is your 150 or 170
});

Upvotes: 2

Related Questions