0

I've got these few lines :

$gifts_offered_in_sub = array();
$gifts_offered_in_final = array();
foreach($gifts_offered_in as $k=>$v) {
    $s = sizeof($v);
    foreach($v as $vk=>$vv) {
        $vv[0] = $s;
    }
    $gifts_offered_in_final[] = $v;
}
var_dump($gifts_offered_in_final);

The gifts_offered_in array contains an array that looks like this :

array(1) {
  [0]=>
  array(2) {
    [220669]=>
    array(2) {
      [0]=>
      string(1) "1"
      [1]=>
      string(1) "1"
    }
    [220664]=>
    array(2) {
      [0]=>
      string(1) "1"
      [1]=>
      string(1) "1"
    }
  }
}

And what I'm trying to achieve is to check for each element in the array (in this instance, there's only 1 element [0] check if the sub array contains more than 1 value, if so, then change the sub array's [0] to contain the size of all to have at the end this result :

array(1) {
  [0]=>
  array(2) {
    [220669]=>
    array(2) {
      [0]=>
      string(1) "2"
      [1]=>
      string(1) "1"
    }
    [220664]=>
    array(2) {
      [0]=>
      string(1) "2"
      [1]=>
      string(1) "1"
    }
  }
}

But it doesn't work, the var_dump is giving me the exact same array as if I didn't change any value in my loop. Any idea what am I doing wrong in my code?

1 Answers1

1

This line only changes your local $vv variable:

$vv[0] = $s;

You should change it to:

$gifts_offered_in[$k][$vk][0] = $s;

And this :

$gifts_offered_in_final[$k] = $gifts_offered_in[$k];

Then you are making the changes in the new $gifts_offered_in_final array that you're building step by step. (Thanks for the Edit suggestion.)

Peter M.
  • 1,240
  • 2
  • 9
  • 25