The problem lies in the correctness of compiling an array of categories and sub categories. Actually the code itself:

The method of creating the tree itself from the array:

public static function getTree($dataset){ $tree = []; foreach ($dataset as $id => &$node) { if (!$node['parent_id']) $tree[$id] = &$node; else $dataset[$node['parent_id']]['childs'][$node['id']] = &$node; } return $tree; } 

The method in which the created tree is used, and, accordingly, the result is displayed:

  public static function getCategoriesList() { $db = Db::getConnection(); $result = $db->query('SELECT id, name, parent_id FROM category WHERE status = "1" ORDER BY sort_order, name ASC'); $i = 0; $categoryList = []; while ($row = $result->fetch()) { $categoryList[$i]['id'] = $row['id']; $categoryList[$i]['name'] = $row['name']; $categoryList[$i]['parent_id'] = $row['parent_id']; $i++; } $tree = Category::getTree($categoryList); echo '<pre>'.print_r($tree, true).'</pre>'; return true; } 

Category table

Category table

And the tree, which turns out:

enter image description here

  • Are you sure that category 1.1 has status = 1 ? - teran pm

1 answer 1

In the getCategoriesList method, the getCategoriesList array is filled with consecutive key numbers ( $i ), and in the getTree method, categories from this array are referenced by the parent category ID ( $dataset[$node['parent_id']] ).
When filling in an array, the $row['id'] category key should be indicated.

 while ($row = $result->fetch()) { $categoryList[$row['id']]['id'] = $row['id']; $categoryList[$row['id']]['name'] = $row['name']; $categoryList[$row['id']]['parent_id'] = $row['parent_id']; } 
  • $categoryList[$row['id']][] = $row - teran pm