Code (PHP) pasted on 2018-07-15, 13:03 Raw Source
- <?php
- // Prepare tree in the controller
- $parents = [];
- foreach ($categories as $category) {
- $key = $category->parent_category_id ?? 0;
- $parents[$key] = [];
- }
- $parents[$key][] = $category;
- }
- return $this->categoryTreeRecursion($parents, $parents[0]);
- }
- private function categoryTreeRecursion($parents, $categories) {
- $tree = [];
- foreach ($categories as $category) {
- $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
- <?php
- $result = '<ul>';
- foreach ($categories as $cat) {
- $children = '';
- $children = printCatTree($cat->children);
- }
- }
- $result .= '</ul>';
- return $result;
- }
- ?>
- <?= printCatTree($categories) ?>