我有一个简单的多维数组。我修改它 - 即。我向它添加数据 - 在 foreach 循环中,通过引用访问其元素:
$array = array(
array('id' => 12, 'name' => 'John1', 'surname' => 'Smith1'),
array('id' => 13, 'name' => 'John2', 'surname' => 'Smith2'),
array('id' => 14, 'name' => 'John3', 'surname' => 'Smith3'),
array('id' => 15, 'name' => 'John4', 'surname' => 'Smith4'),
);
foreach($array as &$a) {
$a['middlename'] = 'Robert';
}
现在下面的内容表明这$array
是完全有序的:
print('<pre>'.print_r($array,true).'</pre>');
结果是:
Array
(
[0] => Array
(
[id] => 12
[name] => John1
[surname] => Smith1
[middlename] => Robert
)
[1] => Array
(
[id] => 13
[name] => John2
[surname] => Smith2
[middlename] => Robert
)
[2] => Array
(
[id] => 14
[name] => John3
[surname] => Smith3
[middlename] => Robert
)
[3] => Array
(
[id] => 15
[name] => John4
[surname] => Smith4
[middlename] => Robert
)
)
但是当我循环它时,内部指针在最后一个元素之前停止:
foreach($array as $a) {
print('<pre>'.print_r($a['id'],true).'</pre>');
}
输出:
12
13
14
14
任何提示发生了什么?
更新:我选择的答案是正确的,而且我发现了这个:PHP Pass by reference in foreach Thx, SO。