在值消失后设置Foreach()值

lin*_*ndy 0 php foreach

我试图使用foreach()循环向现有的数字索引数组添加一个新键.我写了这段代码:

foreach($new['WidgetInstanceSetting'] as $row){
        $row['random_key'] = $this->__str_rand(32, 'alphanum'); 
        debug($row);
    }
    debug($new);
Run Code Online (Sandbox Code Playgroud)

第一个debug()按预期工作:'random_key'在$ new数组中创建.现在,问题是第二个debug()显示$ new数组,但没有新添加的键.为什么会这样?我怎么解决这个问题?

Bol*_*ock 5

$row最终成为foreach块的范围内的副本,所以你真的要修改它的副本而不是原始数组中的副本.

&在你foreach修改$row你的内阵列$new由阵列参考:

foreach($new['WidgetInstanceSetting'] as &$row){
Run Code Online (Sandbox Code Playgroud)

并且正如user576875所说,删除引用$row,以防再次使用该变量以避免不必要的行为,因为PHP将其留下:

foreach($new['WidgetInstanceSetting'] as &$row){
    $row['random_key'] = $this->__str_rand(32, 'alphanum'); 
    debug($row);
}
unset($row);
debug($new);
Run Code Online (Sandbox Code Playgroud)


Gol*_*rol 5

使用&以获取可以更改的引用值.

foreach($new['WidgetInstanceSetting'] as &$row){
        $row['random_key'] = $this->__str_rand(32, 'alphanum'); 
        debug($row);
    }
    debug($new);
Run Code Online (Sandbox Code Playgroud)