I can use it, but I can’t understand it every time I look at it. Can anyone explain and clear it up? &How to understand reference assignment here?
$items = array(
1 => array('id' => 1, 'pid' => 0, 'name' => '安徽省'),
2 => array('id' => 2, 'pid' => 0, 'name' => '浙江省'),
3 => array('id' => 3, 'pid' => 1, 'name' => '合肥市'),
4 => array('id' => 4, 'pid' => 3, 'name' => '长丰县'),
5 => array('id' => 5, 'pid' => 1, 'name' => '安庆市'),
);
function getTree($items){
$tree = array();
foreach($items as $item){
if(isset($items[$item['pid']])){
$items[$item['pid']]['son'][] = &$items[$item['id']];
}else{
$tree[] = &$items[$item['id']];
}
}
return $tree;
}
Mainly the use of references, which can simplify the test:
When quoted:
Without citation:
When there is a reference, changes to the sub-elements will be displayed in the entire array, but when there is no reference, changes to the sub-elements will have no impact on the entire array.
Is there no one here? Please explain
is like this,
items
in the brackets offoreach
=>a
anditems
=>b
in the loop body exist in two places in memory. After using&
,b
will point toa
i.e. the realitems
.But after
php7
,foreach
has changed a bit => php7 foreach is not backward compatibleReference assignment means that the left side of the assignment points directly to the area in the memory where the value is stored, instead of opening up a new space to receive a copy of the data.
So, in the parent-child level relationship, reference assignment directly points the
['son']
in the parent element directly to the storage area of the child element, instead of just storing the value. Each parent element points['son']
to the storage area of the corresponding child element. In this way, it has actually been connected to form a tree structure in the memory. Since all parent elements have['son']
all point to the memory area of the child element , so the parent-child relationship in the output array is basically the same as the data relationship tree in the memory.Reference @vishun
After seeing the above answers, I still want to answer. The use of references in PHP is similar to the usage of pointers in C/C++. It is equivalent to operating the pointer of this variable. In this case, operating the reference variable in the function will also trigger The variable itself changes.
References can bring some benefits: because they operate "pointers" directly, they are very efficient and will not cause unnecessary waste of memory and consume the performance of opening up memory;