为什么在PHP中为数组分配新值会失败?
问题描述:
Consider:
array (size=1)
0 =>
array (size=5)
'name' => string '15268459735 Farming and Projects XXXXX' (length=38)
'region' => string '2' (length=1)
'entitynumber' => string '2012/002086/24' (length=14)
'ownership' => string '6' (length=1)
'id' => string '26249' (length=5)
Why does the following still return the same array without the owner
element?
foreach ($result as $row)
{
$row['owner'] = 1;
}
考虑: p>
array(size = 1)
0 =>
数组(大小= 5)
'名称'=> 字符串'15268459735农业和项目XXXXX'(长度= 38)
'region'=> 字符串'2'(长度= 1)
'entitynumber'=> 字符串'2012/002086/24'(长度= 14)
'所有权'=> 字符串'6'(长度= 1)
'id'=> 字符串'26249'(长度= 5)
code> pre>
为什么以下仍然返回没有 owner code>元素的相同数组? p >
foreach($ result as $ row)
{
$ row ['owner'] = 1;
}
code> pre>
答
Try passing the array by reference:
foreach ($result as &$row) {
$row['owner'] = 1;
}
See also: What's the &
for, anyway?