I am trying to add a new key to an existing numerical indexed array using a foreach() loop. I wrote this piece of code:
foreach($new['WidgetInstanceSetting'] as $row){
$row['random_key'] = $this->__str_rand(32, 'alphanum');
debug($row);
}
debug($new);
The first开发者_运维技巧 debug() works as I expected: the 'random_key' is created in the $new array. Now, the problem is that the second debug() shows the $new array, but without the newly added key. Why is this happening? How can I solve this problem?
$row
ends up being a copy in the scope of the foreach
block, so you really are modifying a copy of it and not what's in the original array at all.
Stick a &
in your foreach
to modify the $row
array within your $new
array by reference:
foreach($new['WidgetInstanceSetting'] as &$row){
And as user576875 says, delete the reference to $row
in case you use that variable again to avoid unwanted behavior, because PHP leaves it around:
foreach($new['WidgetInstanceSetting'] as &$row){
$row['random_key'] = $this->__str_rand(32, 'alphanum');
debug($row);
}
unset($row);
debug($new);
Use the &
to get a by reference value that you can change.
foreach($new['WidgetInstanceSetting'] as &$row){
$row['random_key'] = $this->__str_rand(32, 'alphanum');
debug($row);
}
debug($new);
You need to access the element by reference if you want to modify if within the array, as follows:
foreach($new['WidgetInstanceSetting'] as &$row) {
$row['random_key'] = $this->__str_rand(32, 'alphanum');
}
you are not creating random_key in $new array you are creating it in $row
精彩评论