I have an array that is multiple database tables merged together into an array of the information that is needed. I want to sort this information alphabetically by name and then by id if it is the same name.
I viewed all of the following topics and was not able to produce a working result.
- Sort a multi-dimensional Array in PHP
- sorting a multi-dimensional array
- Sort a multi-dimensional Array in PHP
- http://php.net/manual/en/function.usort.php
MY ARRAY as sudo dump
array(3){
[0] => array(3){
['id'] => "1",
['name'] => "Slippery Sasha",
['type'] => "Electric Eel"
},
[1] => array(3){
['id'] => "2",
['name'] => "Viscious Vipers",
['type'] => "Snake"
},
[2] => array(3){
['id'] => "3",
['name'] => "Finnic Fox",
['type'] => "Rabid Fox"
},
}
Code Attempt
// Sort
$sortByTypes = array('name', 'id', 'type');
usort($returnArray, function($a, $b) use($sortByTypes){
foreach($sortByTypes as $field){
$sort = strnatcasecmp($a[$field], $a[$field]);
if($sort !== 0){
break;
}
}
return $sort;
});
MY INTENDED DUMP
array(3){
[0] => array(3){
['id'] => "3",
['name'] => "Finnic Fox",
['type'] => "Rabid Fox"
},
[1] => array(3){
['id'] => "1",
['name'] => "Slippery Sasha",
['type'] => "Electric Eel"
},
[2] => array(3){
['id'] => "2",
['name'] => "Viscious Vipers",
['type'] => "Snake"
},
}
BONUS IF you can explain how it works and what it is doing to sort the array giving me a better understanding of the feature that would be awesome!