1

I got a multidimensional array which may look like this:

$array[1][0] = "string";
$array[0][1] = "anotherstring";
$array[0][0] = "thirdstring";
$array[1][1] = "fourthstring";

I want to sort this array by keys so it looks like this:

$array[0][0] = "thirdstring";
$array[0][1] = "anotherstring";
$array[1][0] = "string";
$array[1][1] = "fourthstring";

At the moment I am using the following procedure:

ksort($array);
foreach ($array as $key => $value) {
        ksort($value);
        $array[$key] = $value;
}

This does work perfectly, but maybe there is a better (in-built) function to do this?

Zulakis
  • 7,859
  • 10
  • 42
  • 67
  • See [ksort on multidimensional array](http://stackoverflow.com/questions/9017418/ksort-on-multidimensional-array) but I think your 5 lines of code are sufficient. – user1477388 Apr 14 '14 at 20:24
  • array_multisort() is a built in function for multidimensional sorting. In your code, I don't see the need for `$array[$key] = $value;` – Devon Bessemer Apr 14 '14 at 20:24
  • @Devon There is a need for `$array[$key] = $value;` `foreach ($array as &$value) ksort($value);` would not need that – pekkast Apr 14 '14 at 20:28
  • The array is already sorted. Or the example is misleading, being different from what you actually want to sort. – N.B. Apr 14 '14 at 20:33
  • 1
    @Devon ksort($value) changes $value in place; $array[$key]=$value then puts the modified value back into the array. – Brian Kendig Apr 14 '14 at 20:34

1 Answers1

3

You can shorten your loop with:

ksort($array);
foreach($array as &$value) {
        ksort($value);
}

Or use array_walk:

ksort($array);
array_walk($array, 'ksort');
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87