Reputation: 1
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;
}
Upvotes: 0
Views: 1181
Reputation: 46
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 ;)
Upvotes: 0
Reputation: 100
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++;
}
Upvotes: 1