Alexandru Gorgos
Alexandru Gorgos

Reputation: 35

ksort in multidimensional array doesn't work

I'm trying to sort the child arrays of an array by keys. Tried in a loop, doesn't seem to work.

$arr = array (
    15 => array (0=>'london',30=>'rome',21=>'berlin'),
    23 => array (0=>'london',34=>'rome',20=>'berlin'),
    19 => array (0=>'london',31=>'rome',22=>'berlin'),
  );


foreach ($arr as $item) {
    ksort($item);
}

Any idea why?

Upvotes: 0

Views: 325

Answers (1)

jh1711
jh1711

Reputation: 2328

When you modify $item PHP will automatically create a copy and only change that copy. To prevent that you can use a reference:

foreach ($arr as &$item) 

Or you can modify $arrdirectly:

 foreach ($arr as $key => $item) {
   ksort($item);
   $arr[$key] = $item;
 }

Upvotes: 2

Related Questions