Answer the question
In order to leave comments, you need to log in
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
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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question