php - 从parent_id id表结构构建树

标签 php mysql recursion tree

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

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 中收到错误:

Maximum function nesting level of 100 reached, aborting!

我先按 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;
    }
}

关于php - 从parent_id id表结构构建树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24811611/

相关文章:

php - 在 Windows 7 (XAMPP) 中安装内存缓存

php - 构建用于处理时事通讯文章的 Drupal 时事通讯模块

php - 无法使用登录功能

string - Lisp - 仅当符号还不是字符串时才将其转换为字符串

php - 左连接在我准备好的语句中不起作用(mysqli)

php - mysql_fetch_array() : supplied argument is not a valid MySQL result resource in C:\wamp\www\mahesh\login\orderhistory. php 第 48 行

MySQL 从 600K 行中快速选择 10 个随机行

mysql - 从引用表 sql 中查找下一个事件

Javascript:settimeout递归无限堆栈增加?

c++ - C++中的递归函数