Rogue Rogue - 4 months ago 10
PHP Question

Naturally sort a multi-dimensional array by key

I have a multidimensional array in php, and I want to naturally sort the array based on key value. The array in question:

array(27) {
["user1"]=>
array(1) {
["link"]=>
string(24) "http://twitch.tv/example"
}
["someotheruser"]=>
array(1) {
["link"]=>
string(24) "http://twitch.tv/example"
}
["anotheruser"]=>
array(1) {
["link"]=>
string(24) "http://twitch.tv/example"
}
// etc...
}


I have attempted a few things so far, but I am having no luck. Using
uksort
with natsort doesn't work, and I don't want to have to go as far as writing a customer comparator for natural sorting order if I don't have to. I also attempted sorting the keys individually, however that seemed to not work

private function knatsort(&$array) {
$keys = array_keys($array);
natsort($keys);
$new_sort = array();
foreach ($keys as $keys_2) {
$new_sort[$keys_2] = $array[$keys_2];
}
$array = $new_sort;
return true;
}

Answer

Something simpler:

array_multisort(array_keys($array), SORT_NATURAL, $array);

With case insensitivity:

array_multisort(array_keys($array), SORT_NATURAL| SORT_FLAG_CASE, $array);
Comments