Given an array of arrays, how would I natural sort the inner arrays based on their values?
Example array:
array (size=2)
0 =>
array (size=1
PHP's usort() allows you to define a custom callback function for sorting:
usort($array, function($a, $b){
if ($a['manager'] == $b['manager']) {
return 0;
}
return ($a['manager'] < $b['manager']) ? -1 : 1;
});
For sorting months, you can use something like date('m', strtotime($a['month']))
to get the month number for comparison. More ways to do that can be found here: convert month from name to number
You'll can use usort() and write your own comparison function. I started with your example array, then changed the indices to strings just to make sure it worked. I've tested it three ways, and all of them worked, including the array_multisort(if you don't care about keys as you said).
# Quick, dirty, and probably not suitable for any use, anywhere, by anyone
$test1 = array();
$test1["zero"]="June";
$test1["one"] ="January";
function nat_cmp($a,$b){
return strnatcmp($a,$b);
}
#usort($test1, 'nat_cmp'); # Returns {0=>"January",1=>"June"}
#usort($test1, function($a,$b){return strnatcmp($a,$b);}); # Same
array_multisort($test1, SORT_ASC, SORT_NATURAL); #Same
var_dump($test1);
(NB: If you do end up needing the keys, you'll definitely have to go the custom rolled path with array_keys or uksort())
Well!, You can simplify the function using natural sort functions like this:
usort($array, function($a, $b){
return strnatcmp($a['manager'],$b['manager']); //Case sensitive
//return strnatcasecmp($a['manager'],$b['manager']); //Case insensitive
});