Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 207
geerlingguy Avatar asked Sep 13 '10 15:09

geerlingguy


People also ask

How do you sort an array inside an array in PHP?

The arsort() function sorts an associative array in descending order, according to the value. Tip: Use the asort() function to sort an associative array in ascending order, according to the value. Tip: Use the krsort() function to sort an associative array in descending order, according to the key.

How do you sort a specific part of an array?

Arrays. sort() method can be used to sort a subset of the array elements in Java. This method has three arguments i.e. the array to be sorted, the index of the first element of the subset (included in the sorted elements) and the index of the last element of the subset (excluded from the sorted elements).

How do you sort a multidimensional array?

Sorting a multidimensional array by element containing date. Use the usort() function to sort the array. The usort() function is PHP builtin function that sorts a given array using user-defined comparison function. This function assigns new integral keys starting from zero to array elements.

How do you sort an array of objects in PHP?

Approach: The usort() function is an inbuilt function in PHP which is used to sort the array of elements conditionally with a given comparator function. The usort() function can also be used to sort an array of objects by object field.


1 Answers

You can use usort as:

function cmp($a, $b) {    return $a['weight'] - $b['weight']; }  usort($arr,"cmp"); 
like image 134
codaddict Avatar answered Sep 21 '22 00:09

codaddict