How do I sort a PHP array by an element nested inside?
Solution 1
You can use usort
as:
function cmp($a, $b) {
return $a['weight'] - $b['weight'];
}
usort($arr,"cmp");
Solution 2
Can be done using an anonymous function.
Also if your 'weight' is a string use one of the other returns (see the commented out lines):
<?php
$arr = array(
0 => array (
'name' => 'Friday',
'weight' => 6,
),
1 => array (
'name' => 'Monday',
'weight' => 2,
),
);
// sort by 'weight'
usort($arr, function($a, $b) { // anonymous function
// compare numbers only
return $a['weight'] - $b['weight'];
// compare numbers or strings
//return strcmp($a['weight'], $b['weight']);
// compare numbers or strings non-case-sensitive
//return strcmp(strtoupper($a['weight']), strtoupper($b['weight']));
});
var_export($arr);
/*
array (
0 => array (
'name' => 'Monday',
'weight' => 2,
),
1 => array (
'name' => 'Friday',
'weight' => 6,
),
)
*/
Solution 3
You can also use an anonymous function.
usort($items, function($a, $b) {
return $a['name'] > $b['name'];
});
Solution 4
try this: http://php.net/manual/en/function.usort.php
Solution 5
Agree with usort, I also sometimes use array_multisort (http://ca2.php.net/manual/en/function.usort.php) example 3, sorting database results. You could do something like:
<?php
$days = array(
array('name' => 'Friday', 'weight' => 6),
array('name' => 'Monday', 'weight' => 2),
);
$weight = array();
foreach($days as $k => $d) {
$weight[$k] = $d['weight'];
}
print_r($days);
array_multisort($weight, SORT_ASC, $days);
print_r($days);
?>
Output:
Array
(
[0] => Array
(
[name] => Friday
[weight] => 6
)
[1] => Array
(
[name] => Monday
[weight] => 2
)
)
Array
(
[0] => Array
(
[name] => Monday
[weight] => 2
)
[1] => Array
(
[name] => Friday
[weight] => 6
)
)
geerlingguy
I own Midwestern Mac, LLC and consult for large-scale infrastructure projects. I run many websites, have a strong background in Drupal and Ansible, and manage a few services: Hosted Apache Solr Search for Drupal Server Check.in - a simple and inexpensive website and uptime monitor I also spend a lot of time working with infrastructure and cloud ops. I'm the author of Ansible for DevOps and Ansible for Kubernetes.
Updated on July 21, 2022Comments
-
geerlingguy almost 2 years
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.
-
Gumbo over 13 yearsYou can simply use
return $a['weight'] - $b['weight'];
. -
pdolinaj over 9 yearsThis didn't work perfectly for me but this seems total correct solution: