Tell me how best to generate an array, nesting is about 4-5 levels. The structure in the database is as follows. enter image description here

The parent field defines the parent in which the element is nested. Parent-0 is the root node. With the first query I will pull out all the root nodes, the second one already all that are not equal to 0. It is interesting how to construct the array itself with such nesting.

    2 answers 2

    The function itself:

    function buildTree(array $pages, $parent = 0) { $branch = []; foreach ($pages as $page) { if ($page['parent'] == $parent) { $children = buildTree($pages, $page['id_pages']); if ($children) { $page['children'] = $children; } $branch[] = $page; } } return $branch; } 

    Example of use:

     $pages = // SELECT pages $tree = buildTree($pages); 
    • Thank you very much, very useful feature! - quaresma89
      function buildTreeArray($arItems, $section_id = 'Ид_родителя', $element_id = 'Ид') { $childs = array(); if(!is_array($arItems) || empty($arItems)) { return array(); } foreach($arItems as &$item) { if(!$item[$section_id]) { $item[$section_id] = 0; } $childs[$item[$section_id]][] = &$item; } unset($item); foreach($arItems as &$item) { if (isset($childs[$item[$element_id]])) { $item['childs'] = & $childs[$item[$element_id]]; } } return $childs[0]; } 

    Pull out all the data you need in one request

    A source

    • A link forgotten - $ item ['childs'] = & $ childs [$ item [$ element_id]]; - Evgeny Borisov
    • @YevgenyBorisov, thanks, corrected - Artem Y