我正在尝试建立具有确切规格的树。

This Question

基本上,我需要从父级-id表结构创建树。
我正在使用此功能来尝试实现以上目标;

private static function fetch_recursive($src_arr, $currentid = 0, $parentfound = false, $cats = array())
{
    foreach($src_arr as $row)
    {
        if((!$parentfound && $row['category_id'] == $currentid) || $row['parent_id'] == $currentid)
        {
            $rowdata = array();
            foreach($row as $k => $v)
                $rowdata[$k] = $v;
            $cats[] = $rowdata;
            if($row['parent_id'] == $currentid)
                $cats = array_merge($cats, CategoryParentController::fetch_recursive($src_arr, $row['category_id'], true));
        }
    }
    return $cats;
}


但是我从PHP中得到一个错误:


  达到最大功能嵌套级别100,正在中止!


我正在按parent_id排序数据库结果,然后按id排序以解决问题,但它仍然存在。

附带说明,每个表格包含约250条记录。

最佳答案

终于找到了适合我需求的解决方案!感谢大家的所有帮助,也感谢建设性的批评:)

Laravel 4 - Eloquent. Infinite children into usable array?

解:

<?php

class ItemsHelper {

    private $items;

    public function __construct($items) {
      $this->items = $items;
    }

    public function htmlList() {
      return $this->htmlFromArray($this->itemArray());
    }

    private function itemArray() {
      $result = array();
      foreach($this->items as $item) {
        if ($item->parent_id == 0) {
          $result[$item->name] = $this->itemWithChildren($item);
        }
      }
      return $result;
    }

    private function childrenOf($item) {
      $result = array();
      foreach($this->items as $i) {
        if ($i->parent_id == $item->id) {
          $result[] = $i;
        }
      }
      return $result;
    }

    private function itemWithChildren($item) {
      $result = array();
      $children = $this->childrenOf($item);
      foreach ($children as $child) {
        $result[$child->name] = $this->itemWithChildren($child);
      }
      return $result;
    }

    private function htmlFromArray($array) {
      $html = '';
      foreach($array as $k=>$v) {
        $html .= "<ul>";
        $html .= "<li>".$k."</li>";
        if(count($v) > 0) {
          $html .= $this->htmlFromArray($v);
        }
        $html .= "</ul>";
      }
      return $html;
    }
}

10-06 08:20