从 parent_id id 表结构构建树 [英] Build tree from parent_id id table structure

查看:80
本文介绍了从 parent_id id 表结构构建树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to build a tree with the exact specifications of..

这个问题

基本上我需要从父-id 表结构创建一棵树.我正在使用此功能来尝试实现上述功能;

Basically I need to create a tree from a parent - id table structure. I'm using this function to try to achieve the above;

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 的错误:

But I'm getting an error from PHP :

已达到最大函数嵌套级别 100,中止!

Maximum function nesting level of 100 reached, aborting!

我通过 parent_id 和 id 对数据库结果进行排序以帮助解决问题,但问题仍然存在.

I'm ordering the db results by parent_id and then by id to help out with the issue but it still persists.

作为附注,表包含约 250 条记录.

As a side note by table contains ~250 records.

推荐答案

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

Finally found a solution that fits my needs! Thanks for all the help everyone and also for the constructive criticism :)

Laravel 4 - Eloquent.无限子元素变成可用数组?

解决方案:

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

这篇关于从 parent_id id 表结构构建树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆