parent_category_id ?? 0; if (!array_key_exists($key, $parents)) { $parents[$key] = []; } $parents[$key][] = $category; } return $this->categoryTreeRecursion($parents, $parents[0]); } private function categoryTreeRecursion($parents, $categories) { $tree = []; foreach ($categories as $category) { if (array_key_exists($category->id, $parents)) { $category->children = $this->categoryTreeRecursion($parents, $parents[$category->id]); $category->total = ($category->total ?? 0) + array_reduce($category->children, function ($sum, $cat) { return $sum + property_exists($cat, 'total') ? $cat->total : 0; }, 0); } $tree[] = $category; } return $tree; } // Print full category tree in the view '; foreach ($categories as $cat) { $children = ''; if (property_exists($cat, 'children') && is_array($cat->children) && (count($cat->children) > 0)) { $children = printCatTree($cat->children); } $result .= sprintf('
  • %s%s
  • ', $cat->id, $cat->name, $children); } $result .= ''; return $result; } ?>