0

Is it possible to order the below by the value of the child arrays, eg: age or height?

array (
  "John" => array (
    "height"=>175,
    "weight"=>85,
    "age"="24"
  ),
  "Phil" => array (
    "height"=>185,
    "weight"=>75,
    "age"="22"
  )
 "Jim" => array (
    "height"=>195,
    "weight"=>140,
    "age"="29"
  )
)

Eg outputting the order by age would be: Phil, John, Jim.

Is this possible with PHP?

MeltingDog
  • 14,310
  • 43
  • 165
  • 295

4 Answers4

2

Declare a custom function to compare child array and use usort to sort using call back function

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

$a = array(3, 2, 5, 6, 1);

usort($a, "cmp");
Ima
  • 1,111
  • 12
  • 22
2

Use usort: If you are still on PHP 5.2 or earlier, you'll have to define a sorting function first:

function sortByAge($a, $b) {
    return $a['age'] - $b['age'];
}

usort($myArray, 'sortByAge');

Starting in PHP 5.3, you can use an anonymous function:

usort($myArray, function($a, $b) {
    return $a['age'] - $b['age'];
});

And finally with PHP 7 you can use the "spaceship operator":

usort($myArray, function($a, $b) {
    return $a['age'] <=> $b['age'];
});

Source: Sort Multi-dimensional Array by Value

Community
  • 1
  • 1
luchaninov
  • 6,792
  • 6
  • 60
  • 75
  • Forgive my ignorance, but how does this work? Arn't you only comparing 2 ages ($a and $b)? – MeltingDog Oct 24 '16 at 07:58
  • PHP needs to know how to compare any 2 values in array, then it will be able to sort. This is the way you explain to PHP how to compare. – luchaninov Oct 24 '16 at 08:01
1
// sort by height in increasing order
$sorter = function($a,$b){return $a['height']-$b['height'];};

usort($myArr, $sorter);

live demo

BeetleJuice
  • 39,516
  • 19
  • 105
  • 165
0

Use uasort, user-defined sorting that lets you provide your own function to define whether one element should come before another.

http://www.php.net/manual/en/function.uasort.php

Your comparator function would be something like

function cmp($a, $b) {
    return $a['height'] > $b['height'] ? 1 : -1;
}
mahethekiller
  • 514
  • 3
  • 17
  • The comparison function should/must return a value <0, 0, or >0; not just `-1` or `1`. Even if the result may be identical, it's not conforming to the API. In the worst case sorting will be less efficient, since you're not correctly signalling to `usort` when two values are equal. – deceze Oct 24 '16 at 08:38