How do I sort a PHP array by an element nested inside?

geerlingguy picture geerlingguy · Sep 13, 2010 · Viewed 27.1k times · Source

I have an array like the following:

Array
(
    [0] => Array
        (
            'name' => "Friday"
            'weight' => 6
        )
    [1] => Array
        (
            'name' => "Monday"
            'weight' => 2
        )
)

I would like to grab the last values in that array (the 'weight'), and use that to sort the main array elements. So, in this array, I'd want to sort it so the 'Monday' element appears before the 'Friday' element.

Answer

codaddict picture codaddict · Sep 13, 2010

You can use usort as:

function cmp($a, $b) {
   return $a['weight'] - $b['weight'];
}

usort($arr,"cmp");