php多层数组foreach引用和拷贝的取舍
程序员文章站
2022-06-16 07:51:30
...
$a = [ "a"=>["cc"=>11] , "b"=>["cc"=>22] ];
echo "\n".$a['a']["cc"].",".$a['b']["cc"];
$i=1;
//(1)拷贝,$a无变化
foreach($a as $k=>$v) {
$v['cc']=$i;
$i+=1;
}
echo "\n".$a['a']["cc"].",".$a['b']["cc"];
//(2)引用
foreach($a as $k=>&$v) {
$v['cc']=$i;
$i+=1;
}
echo "\n".$a['a']["cc"].",".$a['b']["cc"];
//(3)拷贝
foreach($a as $k=>$v) {
$a[$k]["cc"]=$i;
$i+=1;
}
echo "\n".$a['a']["cc"].",".$a['b']["cc"];
默认foreach是拷贝数组,需要两倍的内存,那性能是不是会很低啊?为什么要这么设计呢
如果数组非常大的情况下,是不是用引用方式会好一些?各自有什么优缺点?
回复内容:
$a = [ "a"=>["cc"=>11] , "b"=>["cc"=>22] ];
echo "\n".$a['a']["cc"].",".$a['b']["cc"];
$i=1;
//(1)拷贝,$a无变化
foreach($a as $k=>$v) {
$v['cc']=$i;
$i+=1;
}
echo "\n".$a['a']["cc"].",".$a['b']["cc"];
//(2)引用
foreach($a as $k=>&$v) {
$v['cc']=$i;
$i+=1;
}
echo "\n".$a['a']["cc"].",".$a['b']["cc"];
//(3)拷贝
foreach($a as $k=>$v) {
$a[$k]["cc"]=$i;
$i+=1;
}
echo "\n".$a['a']["cc"].",".$a['b']["cc"];
默认foreach是拷贝数组,需要两倍的内存,那性能是不是会很低啊?为什么要这么设计呢
如果数组非常大的情况下,是不是用引用方式会好一些?各自有什么优缺点?