PHP Modifying the value of an array element in about foreach

Source: Internet
Author: User

PHP supports the use of reference ' & ', the use of the same as C basically, the personal understanding is that the function refers to the variable pointer directly to the source address of the incoming parameter, so using the reference is still a certain danger. Therefore, for a heavy loop, it is recommended that you do not use references to modify the original array directly

        $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 '; }        EchoJson_encode ($table _exchange);

Output:

[{"Cnid": "222", "status": 0, "checked": false, "leaf": true}]

In a complex multi-loop operation, the use of references is much easier and easier to understand and manipulate, for example:

         $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 $b 2=>&$d){                $d[' Cnid ']= ' 000 '; }        }                EchoJson_encode ($table _exchange);//convert to JSON format output to Web page display results

Output: [{' Cnid ': ' 2 ', ' status ': 0, ' checked ': false, ' children ': [{' Cnid ': ' $ ', ' status ': 1, ' checked ': false, ' leaf ': true}], "Leaf": true}]

PHP Modifying the value of an array element in about foreach

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.