Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 custom 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;
}
like image 600
Rogue Avatar asked Dec 06 '13 18:12

Rogue


1 Answers

Something simpler. Extract the array keys and sort those, sorting the original by that:

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

With case insensitivity:

array_multisort(array_keys($array), SORT_NATURAL | SORT_FLAG_CASE, $array);
like image 184
AbraCadaver Avatar answered Oct 29 '22 21:10

AbraCadaver