Home > Blockchain >  Add new data in foreach loop multidimensional array
Add new data in foreach loop multidimensional array

Time:12-30

I try to add new data in a multidimensional array for each loop, but it wont work.

This shows the values in my array:

   $keys = array_keys($klanten);
    for($i = 0; $i < count($klanten); $i  ) {
      foreach($klanten[$keys[$i]] as $key => $value) {
            echo $key . " : " . $value . "<br>";
            $klanten['newData'] = 'test';
        }
     }

With $klanten['newData'] = 'test'; I try to add "test" to each array, but it won't work.

I also tried to use this, AFTER the script above:

    foreach ($klanten as &$item ){
        $item['newData'] = 'test';
    }

That will work, but I think there must be an option to do it in the foreach loop above the first time. How can I do that?

CodePudding user response:

Hi so you got most of it right but, you see when you are looping around a variable and adding a new item in it you have to make sure to give a index for that new array index so...

$keys = array_keys($klanten);
for($i = 0; $i < count($klanten); $i  ) {
  foreach($klanten[$keys[$i]] as $key => $value) {
        echo $key . " : " . $value . "<br>";
        // $klanten['newData'] = 'test'; // instead of this
        $klanten[$key]['newData'] = 'test'; // do this
    }
 }

This will save each and every value of newData index according to its key in $klanten array.

  • Related