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

foreach 遍历为什么会出错?

WBOY
Release: 2016-06-23 13:25:42
Original
918 people have browsed it

看到网友的帖子,自己试了试,果然如化所说,但不知为什么。请高手指教。
$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);
Copy after login
Array(    [0] => Array        (            [titledata] => BB            [bodydata] => CC        )    [1] => Array        (            [titledata] => BB            [bodydata] => CC        ))
Copy after login
原因很简单,foreach($blog as $b) 得到的是副本,你在副本上改写,不会影响到正本

高,佩服!谢谢。

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