["cc"=>11] , "b"=>["cc"=>22] ];echo "\n".$a['a']["cc"].",".$a['b']["cc"];$i=1;//(1)拷贝,$a无变化foreach($a as $k">
当前位置:Gxlcms > PHP教程 > php多层数组foreach引用和拷贝的取舍

php多层数组foreach引用和拷贝的取舍

时间:2021-07-01 10:21:17 帮助过:5人阅读

$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是拷贝数组,需要两倍的内存,那性能是不是会很低啊?为什么要这么设计呢
如果数组非常大的情况下,是不是用引用方式会好一些?各自有什么优缺点?

人气教程排行