从parent_id id表结构构建树

时间:2014-07-17 19:09:51

标签: php mysql recursion tree

我正在尝试使用确切的规格构建一棵树..

This Question

基本上我需要从parent-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条记录。

1 个答案:

答案 0 :(得分:1)

终于找到了符合我需求的解决方案!感谢所有人的帮助以及建设性的批评:)

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;
    }
}