首页 > 代码库 > PHP 关于foreach 中修改array中元素的值

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}]

PHP 关于foreach 中修改array中元素的值