Naturally sort a multidimensional array by key

I have a multidimensional array in php and I want to naturally sort the array based on the 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...
}

So far, I have been trying to do a few things, but I'm out of luck. Using uksortwith natsort doesn't work, and I don't want to go as far as writing my own comparator for a natural sort order if I don't need to. I also tried to sort the keys individually, but that didn't help.

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;
}
+5
source share
4 answers

Something simpler. Extract the array keys and sort them, sorting the original:

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

Case insensitive:

array_multisort(array_keys($array), SORT_NATURAL| SORT_FLAG_CASE, $array);
+14

strnatcmp(); :

function knatsort(&$arr){return uksort($arr,function($a, $b){return strnatcmp($a,$b);});}

uksort. :

knatsort($array);

:)

+4

@AbraCadaver , , , .

array_multisort(array_keys($this->streams), SORT_NATURAL | SORT_FLAG_CASE , $this->streams);

$this->streams - . , .

+1

, array_multisort: ksort :

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

ksort($arr, SORT_NATURAL);

:

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

, :

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

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

All Articles