Heim >Backend-Entwicklung >PHP-Tutorial >foreach 遍历为什么会出错?
看到网友的帖子,自己试了试,果然如化所说,但不知为什么。请高手指教。
$blog=array(
array(
"titledata"=>"titleMM",
"bodydata"=>"bodyMM"
),
array(
"titledata"=>"titleGG",
"bodydata"=>"bodyGG"
)
);
//出错
foreach($blog as $b)
{
$b['titledata']="BB";
$b['bodydata']="CC";
}
print_r($blog); //显示Array ( [0] => Array ( [titledata] => titleMM [bodydata] => bodyMM ) [1] => Array ( [titledata] => titleGG [bodydata] => bodyGG ) ),得不到预期的结果。
//正确
for($i=0;$i
$blog[$i]['titledata']="title";
$blog[$i]['bodydata']="body";
}
print_r($blog);//得到预期的结果:Array ( [0] => Array ( [titledata] => title [bodydata] => body ) [1] => Array ( [titledata] => title [bodydata] => body ) )
?>
$blog=array( array( "titledata"=>"titleMM", "bodydata"=>"bodyMM" ), array( "titledata"=>"titleGG", "bodydata"=>"bodyGG" ) ); foreach($blog as &$b) { $b['titledata']="BB"; $b['bodydata']="CC"; } print_r($blog);
Array( [0] => Array ( [titledata] => BB [bodydata] => CC ) [1] => Array ( [titledata] => BB [bodydata] => CC ))原因很简单,foreach($blog as $b) 得到的是副本,你在副本上改写,不会影响到正本
高,佩服!谢谢。