Table of Contents
Cause:
Practise
Analysis
Home Backend Development PHP Tutorial Re-understanding PHP references

Re-understanding PHP references

Apr 14, 2018 pm 02:51 PM
php Quote understand

This article mainly introduces the re-understanding of PHP references. It has a certain reference value. Now I share it with everyone. Friends in need can refer to it.

Cause:

In daily development, We will encounter the need to construct a tree, build a tree structure through the relationship between id and pid, and then traverse the tree and other operations. There are two ways to implement it: 1. Recursion, 2. Reference
The advantages and disadvantages of these two methods are also obvious.

  1. Recursion is easier to implement, but as the amount of counting data increases, its performance is very low.

  2. The concept of citation itself is easy to understand and its performance is also very good, but there are still certain thresholds for using it well, and it is not easy to write.

The reason for writing this article is that I came across a very good solution in the past few days, which made me understand quotation again. Through this article, summarize your learning results. Ok, then go directly to the code.

Practise

If you can understand the following code after reading it, it means that you are really knowledgeable in quoting. You can also skip this article directly~.
function buildTreeByReference($data, $id = 'id', $pid = 'pid', $child = "children")
    {
        $tmp = []; //以id为健,$value为值的容器,可以很巧妙的判断根节点元素
        $tree = [];  
        //利用引用,对$data的数据进行操作
        foreach ($data as $key => &$value) {
                // 
                $tmp[$value['id']] = &$value;
                
                if (!isset($tmp[$value['pid']])) {
                    $tree[] = &$tmp[$value['id']];
                }else {
                     $temp = &$tmp[$value['pid']];
                     $temp[$child][] = &$value;
                }
                unset($temp, $value);
        }
        return $tree;
    }
Copy after login

ok, let’s not talk about other things first. You can test this method with the following data.

$data= [
            ["id" => 1, "pid" => 0 , "name" => 'Universe'],
            ["id" => 2, "pid" => 1 , "name" => 'Earth'],
            ["id" => 3, "pid" => 2 , "name" => 'China'],
            ["id" => 4, "pid" => 3 , "name" => 'Beijing'],
];
Copy after login
Additional note: This method needs to pay attention to the fact that the parent node needs to be in front. It is not suitable for unordered data, so if it is unordered, it must be sorted first.

If there are no accidents, the printed result should be as follows:

array(1) {
  [0]=>
  array(4) {
    ["id"]=>
    int(1)
    ["pid"]=>
    int(0)
    ["name"]=>
    string(8) "Universe"
    ["children"]=>
    array(1) {
      [0]=>
      array(4) {
        ["id"]=>
        int(2)
        ["pid"]=>
        int(1)
        ["name"]=>
        string(5) "Earth"
        ["children"]=>
        array(1) {
          [0]=>
          array(4) {
            ["id"]=>
            int(3)
            ["pid"]=>
            int(2)
            ["name"]=>
            string(5) "China"
            ["children"]=>
            array(1) {
              [0]=>
              array(3) {
                ["id"]=>
                int(4)
                ["pid"]=>
                int(3)
                ["name"]=>
                string(7) "Beijing"
              }
            }
          }
        }
      }
    }
  }
}
Copy after login

If you are here, you still If you don’t understand, it doesn’t matter. Let’s analyze it one by one.
In fact, to completely understand this solution, you need to understand two parts.

  1. foreach assignment principle

  2. Quoted principle

foreach
    $data = ["student", "teacher"];
    foreach ($data as $index => $item) {
    }
Copy after login

Note that each time the loop is executed, the "values" of $data[0] and $data[1] are copied and then assigned to $item

Quote (Be sure to try it yourself)
$a = 1;
$b = &$a;
$c = $b;
$c = 2;
猜猜看 $b = ?;
Copy after login

If you have any questions about the quote, click here

If you can understand the above foreach and quote, and understand All the implementation process of this solution, then congratulations, you have learned so well! But if you still have difficulties, it doesn’t matter, let’s do it step by step.

Analysis

ok, Take a deep breath and follow my thoughts, let’s go step by step.

  1. First let’s take a look at the original function

function buildTreeByReference($data, $id = 'id', $pid = 'pid', $child = "children")
    {
        $tmp = []; #以id为健,$value为值的容器,可以很巧妙的判断根节点元素
        $tree = [];  
        #利用引用,对$data的数据进行操作
        foreach ($data as $key => &$value) {
                
                #&$value取到$data元素对应值的引用
                
                $tmp[$value['id']] = &$value;
                
                #以$value['id']为键,&$value引用为值push到$tmp中,
                #这样可以巧妙的判断当前元素是否为根节点
                
                if (!isset($tmp[$value['pid']])) {
                    #将根节点push到$tree中
                    $tree[] = &$tmp[$value['id']];
                    
                }else {
                     #若当前元素的父节点存在于$tmp中, 引用获取$tmp中对应父节点的值
                     $temp = &$tmp[$value['pid']];
                     #然后将当前元素push到其父节点的children中
                     $temp[$child][] = &$value;
                }
                #为了不引起变量污染, 引用用完后,需要unset掉
                unset($temp, $value);
        }
        return $tree;
    }
Copy after login
  1. First loop

function buildTreeByReference($data, $id = 'id', $pid = 'pid', $child = "children")
    {
       # $tmp = [];
       # $tree = [];  
        
       # foreach ($data as $key => &$value) {
                // 
                $tmp[$value['id']] = &$value;
                
                if (!isset($tmp[$value['pid']])) {
                    $tree[] = &$tmp[$value['id']];
                }else {
        #             $temp = &$tmp[$value['pid']];
        #             $temp[$child][] = &$value;
        #        }
                unset($temp, $value);
        }
        return $tree;
    }
Copy after login

Variable situation:
$data[0] = ["id" => 1, "pid" = > 0 , "name" => 'Universe'];
$tmp[1] = &$data[0];
$tree[] = &$data[0]

  1. Second loop

function buildTreeByReference($data, $id = 'id', $pid = 'pid', $child = "children")
    {
       # $tmp = [];
       # $tree = [];  
        
       # foreach ($data as $key => &$value) {
                // 
                $tmp[$value['id']] = &$value;
                
        #        if (!isset($tmp[$value['pid']])) {
        #            $tree[] = &$tmp[$value['id']];
                }else {
                     $temp = &$tmp[$value['pid']];
                     $temp[$child][] = &$value;
                }
                unset($temp, $value);
        }
        return $tree;
    }
Copy after login
Copy after login
Copy after login

Variable situation:
$data[1] = ["id" => 2 , "pid" => 1 , "name" => 'Earth'];
$value=&$data[1];
$tmp[2] = &$data[1];
Note:
$temp is &$tmp[1], which points to the same address as $data[0]
So $temp['children'][] = &$ value , the result of the operation is:

$data[
    [  
     "id" => 1,
     "pid" => 0 ,
     "name" => 'Universe'
     "children"=>[
                 &$data[1],   //注意:存储的是引用
         ]
     ]   
     ...
]
Copy after login
Copy after login

4. The third loop

function buildTreeByReference($data, $id = 'id', $pid = 'pid', $child = "children")
    {
       # $tmp = [];
       # $tree = [];  
        
       # foreach ($data as $key => &$value) {
                // 
                $tmp[$value['id']] = &$value;
                
        #        if (!isset($tmp[$value['pid']])) {
        #            $tree[] = &$tmp[$value['id']];
                }else {
                     $temp = &$tmp[$value['pid']];
                     $temp[$child][] = &$value;
                }
                unset($temp, $value);
        }
        return $tree;
    }
Copy after login
Copy after login
Copy after login

variable situation:
$data[2] = ["id" = > 3, "pid" => 2 , "name" => 'China'];
$value = &$data[2];
$tmp[3] = &$data[2 ];
Note:
$temp is &$tmp[2], which points to the same address as $data[1]

So $temp['children' ][] = &$value , the result of the operation is:
Note here:
This is the reference to $data[1] stored in children during the second cycle

$data[
    [  
     "id" => 1,
     "pid" => 0 ,
     "name" => 'Universe'
     "children"=>[
                 &$data[1],   //注意:存储的是引用
         ]
     ]   
     ...
]
Copy after login
Copy after login

In the third loop, it is $data[1]['children'][] = &$value, and $value points to $data[2]
, so the result is:

   $data[
        [  
         "id" => 1,
         "pid" => 0 ,
         "name" => 'Universe'
         "children"=>[
                       // &$data[1],   //注意:存储的是引用
                         [
                           "id" => 2, 
                           "pid" => 1 ,
                           "name" => 'Earth'
                           "children" => [
                                   &data[2] //注意:存储的是引用   
                            ]
                         
                         ] 
                         
                     ]
             ]
         ]   
         ...
    ]
Copy after login
Copy after login

5. The fourth cycle

function buildTreeByReference($data, $id = 'id', $pid = 'pid', $child = "children")
    {
       # $tmp = [];
       # $tree = [];  
        
       # foreach ($data as $key => &$value) {
                // 
                $tmp[$value['id']] = &$value;
                
        #        if (!isset($tmp[$value['pid']])) {
        #            $tree[] = &$tmp[$value['id']];
                }else {
                     $temp = &$tmp[$value['pid']];
                     $temp[$child][] = &$value;
                }
                unset($temp, $value);
        }
        return $tree;
    }
Copy after login
Copy after login
Copy after login

Variable situation:
$data[3] = ["id" => 4, "pid" => 3 , "name" => 'Beijing'];
$value = &$data[3];
$tmp[3] = &$data[3];
Note:
$temp is &$tmp[2], which points to the same address as $data[1]

So $temp['children'][] = &$value, the result of the operation Yes:
Note here:
This is the reference to $data[2] stored in children during the third cycle.

   $data[
        [  
         "id" => 1,
         "pid" => 0 ,
         "name" => 'Universe'
         "children"=>[
                       // &$data[1],   //注意:存储的是引用
                         [
                           "id" => 2, 
                           "pid" => 1 ,
                           "name" => 'Earth'
                           "children" => [
                                   &data[2] //注意:存储的是引用   
                            ]
                         
                         ] 
                         
                     ]
             ]
         ]   
         ...
    ]
Copy after login
Copy after login

During the fourth cycle, it is $ data[2]['children'][] = &$value, and $value points to $data[3]
, so the result is:

   $data[
        [  
         "id" => 1,
         "pid" => 0 ,
         "name" => 'Universe'
         "children"=>[
                       // &$data[1],   //注意:存储的是引用
                         [
                           "id" => 2, 
                           "pid" => 1 ,
                           "name" => 'Earth'
                           "children" => [
                                  // &data[2] //注意:存储的是引用 
                                  [
                                      "id" => 3,
                                      "pid" => 2 ,
                                      "name" => 'China' 
                                      "children" =>[
                                                 &$data[3];  //注意:存储的是引用                            
                                      ]
                                  ]  
                            ]
                         
                         ] 
                         
                     ]
             ]
         ]   
         ...
    ]
Copy after login

ok. At this point, the entire execution process goes Got it, do you understand? :)

By the way, there is another method, which is also through reference. I will not analyze this. If you understand the above method, the following one is relatively simple.

    public static function buildTreeByReference1($data, $id = 'id', $pid = 'pid', $child = "children")
    {
        $tmp = [];
        
        foreach ($data as $key => $value) {
            $tmp[$value[$id]] = $value;
        }
        $tree = [];
        foreach ($tmp as $key => $value) {
                if (isset($tmp[$value['pid']])) {
                    $tmp[$value['pid']]['children'][] = &$tmp[$key];
                }else{
                    $tree[] = &$tmp[$key];    
                }
        }
        return $tree;
    }
Copy after login

Related recommendations:

A summary of several usage examples cited by php                                            

The above is the detailed content of Re-understanding PHP references. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles