1

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.

4
  • you can try array_map() that will sort each array inside the parent array . Commented Nov 28, 2015 at 9:52
  • Why to use array_map if you can simply use usort or uasort Commented Nov 28, 2015 at 10:17
  • Sorry, I should have said there can be more then two 'sets' of distance & id values. I don't think using usort in that case would be feasible. Commented Nov 28, 2015 at 12:27
  • @RyanVincent Sorry - yes that does work. I assumed that usort would only work for nested arrays. Paste here: pastebin.com/XwCNPaMN Commented Nov 28, 2015 at 13:22

1 Answer 1

2

use usort

usort($yourArray, function($a, $b) {
    return $a[0] - $b[0]; // index 0 is your 150 or 170
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.