Naturally sort a multi-dimensional array by key

Viewed 9062

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;
}
4 Answers

Even simpler than using array_multisort: you can actually provide a sort flag to the built-in ksort function to make it sort an array by key in natural order:

$arr = array(
    "CFoo" => "xx1",
    "AFoo" => "xx2",
    "1Foo" => "xx3",
    "10AFoo" => "xx4"
);

ksort($arr, SORT_NATURAL);

Yields:

Array
(
    [1Foo] => xx3
    [10AFoo] => xx4
    [AFoo] => xx2
    [CFoo] => xx1
)

If you want to apply it recursively to a multidimensional array, you can write a simple function for that:

function natksort_multi(&$arr = array()) {
    ksort($arr, SORT_NATURAL);

    foreach (array_keys($arr) as $key) {
        if (is_array($arr[$key])) {
            natksort_multi($arr[$key]);
        }
    }
}
Related