Link.FYI

Pastebin

Create New My Pastes

Code (PHP) pasted on 2018-07-15, 13:03 Raw Source

  1. <?php
  2. // Prepare tree in the controller
  3.  
  4.     private function buildCategoryTree(array $categories): array {
  5.         $parents = [];
  6.         foreach ($categories as $category) {
  7.             $key = $category->parent_category_id ?? 0;
  8.             if (!array_key_exists($key, $parents)) {
  9.                 $parents[$key] = [];
  10.             }
  11.             $parents[$key][] = $category;
  12.         }
  13.         return $this->categoryTreeRecursion($parents, $parents[0]);
  14.     }
  15.  
  16.     private function categoryTreeRecursion($parents, $categories) {
  17.         $tree = [];
  18.         foreach ($categories as $category) {
  19.             if (array_key_exists($category->id, $parents)) {
  20.                 $category->children = $this->categoryTreeRecursion($parents, $parents[$category->id]);
  21.                 $category->total = ($category->total ?? 0) + array_reduce($category->children, function ($sum, $cat) {
  22.                         return $sum + property_exists($cat, 'total') ? $cat->total : 0;
  23.                     }, 0);
  24.             }
  25.             $tree[] = $category;
  26.         }
  27.         return $tree;
  28.     }
  29.  
  30.  
  31. // Print full category tree in the view
  32.  
  33.         <?php
  34.         function printCatTree(array $categories) {
  35.             $result = '<ul>';
  36.             foreach ($categories as $cat) {
  37.                 $children = '';
  38.                 if (property_exists($cat, 'children') && is_array($cat->children) && (count($cat->children) > 0)) {
  39.                     $children = printCatTree($cat->children);
  40.                 }
  41.                 $result .= sprintf('<li data-category-id="%d">%s%s</li>', $cat->id, $cat->name, $children);
  42.             }
  43.             $result .= '</ul>';
  44.             return $result;
  45.         }
  46.  
  47.         ?>
  48.         <?= printCatTree($categories) ?>