Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I numerically sort a nested array?

I have a 2D array that looks like this:

array(2) {
  [45]=>
  array(5) {
    [0]=>
    int(2)
    [1]=>
    int(5)
    [2]=>
    int(1)
    [3]=>
    int(3)
    [4]=>
    int(4)
  }
  [42]=>
  array(5) {
    [0]=>
    int(5)
    [1]=>
    int(4)
    [2]=>
    int(3)
    [3]=>
    int(2)
    [4]=>
    int(1)
  }
}

The key values of the outer array are numerical, but do not start at 0, and are not sequential. I want to sort the outer array by ascending keys, and the inner arrays by ascending values, so I try this:

ksort($arr);
foreach ($arr as $a) {
    sort($a);
}
var_dump($arr);

Which sorts the outer array as expected, but doesn't seem to touch the inner arrays at all:

array(2) {
  [42]=>
  array(5) {
    [0]=>
    int(5)
    [1]=>
    int(4)
    [2]=>
    int(3)
    [3]=>
    int(2)
    [4]=>
    int(1)
  }
  [45]=>
  array(5) {
    [0]=>
    int(2)
    [1]=>
    int(5)
    [2]=>
    int(1)
    [3]=>
    int(3)
    [4]=>
    int(4)
  }
}

Why is this, and how can I achieve what I want? I think it's something to do with the array being nested, because the following works as expected:

$test = array(5,2,3,1,4);
sort($test);
var_dump($test);

array(5) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
  [4]=>
  int(5)
}
like image 863
shanethehat Avatar asked Sep 19 '26 06:09

shanethehat


1 Answers

foreach iterates over a copy of the array. If you want to modify the actual values, you have to reference them:

//               v
foreach ($arr as &$a) {
    sort($a);
}
unset($a);

From the documentation:

As of PHP 5, you can easily modify array's elements by preceding $value with &. This will assign reference instead of copying the value.

like image 194
Felix Kling Avatar answered Sep 21 '26 21:09

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!