0

In PHP7, how to sort recursively all levels of the array to have any adjacent keys to be in lexicographical order?

This sample array:

$a = ['c'=>['d'=>1, 'a'=>2], 'b'=>['b'=>3, 'a'=>4], 'a'=>['z','x','y']];

I'm looking to translate to:

$a = ['a'=>['z','x','y'], 'b'=>['a'=>4, 'b'=>3], 'c'=>['a'=>2, 'd'=>1]];
ppmag
  • 75
  • 9
  • 1
    Possible duplicate of [PHP Need to recursively reverse an array](https://stackoverflow.com/questions/4103856/php-need-to-recursively-reverse-an-array) – scrowler Sep 26 '18 at 15:35
  • Similar approach, but bit different. – ppmag Sep 26 '18 at 16:54

1 Answers1

1

Finally, solved it.

$a = ['c'=>['d'=>1, 'a'=>2], 'b'=>['b'=>3, 'a'=>4], 'a'=>['z','x','y']];

function array_sort_recursive($arr) {
    foreach ($arr as $key => $val) {
        if (is_array($val))
            $arr[$key] = array_sort_recursive($val);
    }
    uksort($arr, "strcmp");
    return $arr;
}

$b = array_sort_recursive($a);
print_r($b);

Try it: here

ppmag
  • 75
  • 9