gpt4 book ai didi

php - 从parent_id id表结构构建树

转载 作者:行者123 更新时间:2023-11-29 12:50:31 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com