PHP 关于foreach 中修改array中元素的值
PHP中支持使用引用‘&‘,用法与C基本一样,个人理解就是函数中引用的变量指针直接指向了传入参数的源地址,所以使用引用还是存在一定的危险性。所以对于一重循环,建议不使用引用,直接修改原array即可
$table_exchange=array(); array_push($table_exchange, array( "cnid" => ‘123‘, "status" => 0, "checked" => false, "leaf" => true )); foreach ($table_exchange as $b=> $c) { $table_exchange[$b][‘cnid‘]= ‘222‘; } echo json_encode($table_exchange);
输出:
[{"cnid":"222","status":0,"checked":false,"leaf":true}]
而在操作复杂的多重循环中,使用引用会方便许多,也更加便于理解和操作,例如:
$nodeList=array(); array_push($nodeList, array( "cnid" => ‘1‘, "status" => 1, "checked" => false, "leaf" => true )); $table_exchange=array(); array_push($table_exchange, array( "cnid" => ‘2‘, "status" => 0, "checked" => false, "children" => $nodeList, "leaf" => false )); foreach ($table_exchange as $b=>& $c){ foreach($c[‘children‘] as $b2=>& $d){ $d[‘cnid‘]=‘000‘; } } echo json_encode($table_exchange);//转成json格式输出到网页显示结果
输出:[{"cnid":"2","status":0,"checked":false,"children":[{"cnid":"000","status":1,"checked":false,"leaf":true}],"leaf":true}]
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。