V
V
Vadim2015-10-28 00:05:54
PHP
Vadim, 2015-10-28 00:05:54

How to understand a code snippet?

Help me understand how the code works step by step? It is clear that this code sorts the original array taking into account the hierarchy. But I can't figure out exactly how.

$array = array ( 
  array('id' => 1,'parent' => 0,'title' => 'Ветка 1'), 
  array('id' => 2,'parent' => 1,'title' => 'Ветка 1.1'), 
  array('id' => 3,'parent' => 2,'title' => 'Ветка 1.1.1'), 
  array('id' => 4,'parent' => 1,'title' => 'Ветка 1.2'), 
  array('id' => 5,'parent' => 3,'title' => 'Ветка 1.2.1'), 
  array('id' => 6,'parent' => 4,'title' => 'Ветка 1.2.1.1'), 
); 

$tree = array(); 
$sub = array( 0 => &$tree ); 

foreach ($array as $item) 
{ 
    $id = $item['id']; 
    $parent = $item['parent']; 

    $child = &$sub[$parent];
    $child[$id] = array(); 
    $sub[$id] = &$child[$id]; 
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Aleksey Ratnikov, 2015-10-28
@mahoho

References inside arrays are described in the documentation:
php.net/manual/ru/language.references.whatdo.php.
And this code does not sort anything, but creates a tree of empty arrays in $tree based on the id and parent_id values ​​in the original arrays. If you change the order of the elements in places in the original array, everything will break.

S
Sergey, 2015-10-28
@gangstarcj

put in a loop print_r($var); and display what you want to watch

S
Sergey, 2015-10-28
Protko @Fesor

watch the value of the $sub variable. A spoiler is a link that we constantly change in a loop, a pointer to the current element of the tree.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question