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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM