0

I've got a large json of data that needs to be maniputlated. I'm trying to add two key value pairs to each array inside of a foreach loop. It's works inside the loop but doesn't seem to save the array values outside of the loop.

This is what I've tried but it just doesn't seem to be working.

  foreach ($data as $array) {
            $array['value1'] = 0;
            $array['value2'] = 0;
        }
vlcdlc
  • 1
  • Use different variable inside the loop, but not `$array`, i.e. define a new array outside and then assign values to it. `array` is being overwritten on each loop's iteration. – mitkosoft Jan 14 '20 at 13:44

2 Answers2

1

You can use this way;

  $newArray = array();
  $i = 0;
  foreach ($data as $array) {
        $newArray[$i] = $array;
        $newArray[$i]['value1'] = 0;
        $newArray[$i]['value2'] = 0;
        $i++;
    }
Serdar
  • 100
  • 1
  • 5
0

From the documentation:

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

So you have 2 options to fix this:

foreach($data as &$array){

or:

  foreach ($data as $key => $array) {
      $data[$key]['value1'] = 0;
      $data[$key]['value2'] = 0;
  }

Anyway you can find similar questions on SO so try searching first ;)

Mike
  • 46
  • 1
  • 4