PHP 關於foreach 中修改array中元素的值

來源:互聯網
上載者:User

標籤:style   blog   ar   color   使用   sp   for   on   div   

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中元素的值

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.