Rumah > Artikel > pembangunan bahagian belakang > foreach 遍历为什么会报错
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( <br /> array( <br /> "titledata"=>"titleMM", <br /> "bodydata"=>"bodyMM" <br /> ), <br /> array( <br /> "titledata"=>"titleGG", <br /> "bodydata"=>"bodyGG" <br /> ) <br />); <br /><br />foreach($blog as &$b) <br />{ <br /> $b['titledata']="BB"; <br /> $b['bodydata']="CC"; <br />} <br />print_r($blog);
Array<br />(<br /> [0] => Array<br /> (<br /> [titledata] => BB<br /> [bodydata] => CC<br /> )<br /><br /> [1] => Array<br /> (<br /> [titledata] => BB<br /> [bodydata] => CC<br /> )<br /><br />)<br /><br />原因很简单,foreach($blog as $b) 得到的是副本,你在副本上改写,不会影响到正本