A-A+
PHP: foreach用法的常见错误
一、给二维数组添加元素
错误做法:
foreach ($myaddr as $k=>$line){
$line['str'] = $line['province'].$line['city'].$line['county'].$line['address'];
}
错误原因:$k和$line在foreach里面是虚拟变量
正确做法1:
foreach ($myaddr as $k=>$line){
$myaddr[$k]['str'] = $myaddr[$k]['province'].$myaddr[$k]['city'].$myaddr[$k]['county'].$myaddr[$k]['address'];
}
正确做法2:给$line添加引用符号&
foreach ($myaddr as &$line){
$line['str'] = $line['province'].$line['city'].$line['county'].$line['address'];
}