Home > Backend Development > PHP Tutorial > foreach 遍历为什么会报错

foreach 遍历为什么会报错

WBOY
Release: 2016-06-13 12:25:23
Original
1912 people have browsed it

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);
Copy after login
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 />
Copy after login
原因很简单,foreach($blog as $b) 得到的是副本,你在副本上改写,不会影响到正本

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template