0

I have the following array:

Array ( [0] => Array 
               ( [name] => Jonah 
                 [age] => 27 )
        [1] => Array 
               ( [name] => Bianca 
                 [age] => 32 )
      )

Is it possible to sort the sub-array values in [age] into some sort of order, such as lowest to highest or vice versa?

0

3 Answers 3

6

You can do this using usort:

usort($arr, function($a, $b)
{
    return $a['age'] - $b['age']; // sorts lowest to highest
});

Swap $a and $b in the function to reverse the ordering.

Sign up to request clarification or add additional context in comments.

Comments

0

I think this should be possible with bool usort ( array &$array , callback $cmp_function )

http://php.net/manual/en/function.usort.php

Just define a callback that sorts by the [age] key of the value.

Comments

0

This will work:

$ages = array();
foreach ($array as $value) {
  $ages[] = $value;
}

array_multisort($values, SORT_ASC, $array);

Any way is good, but this is the "PHP way":

array_multisort() can be used to sort several arrays at once, or a multi-dimensional array by one or more dimensions.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.