gpt4 book ai didi

php - 列出父子树结构

转载 作者:行者123 更新时间:2023-11-29 23:38:04 24 4
gpt4 key购买 nike

我有多层父子关系,我想以树结构列出它们。我有一个包含 id、parent_id 等字段的表。我尝试过

$sql    = 'SELECT * FROM list WHERE parent_id = 0';
$result = mysql_query($sql, $link);
while ($row = mysql_fetch_array($result)) {
echo $row['id'].'<br>';
$child1_sql = "SELECT * FROM list WHERE parent_id = ".$row['id'];
$result1 = mysql_query($child1_sql, $link);
while ($row1 = mysql_fetch_array($result1)) {
$id = my_recursive_function($row1['parent_id'],$link);
echo $id;
}
}

function my_recursive_function($parent_id,$link) {

$child2_sql = "SELECT * FROM list WHERE parent_id = ".$parent_id;
$result2 = mysql_query($child2_sql, $link);
$row_cnt = mysql_num_rows($result2);

if($row_cnt > 0) {
while ($row = mysql_fetch_array($result2)) {
if($row['parent_id'] == 0) {
return $row['id'];
} else {
my_recursive_function($row['parent_id'],$link);
}
}
}
}

但它给了我

Fatal error:  Out of memory (allocated 126877696) (tried to allocate 24 bytes)

最佳答案

你应该优化sql查询,而不是使用php递归。有一篇关于此的好文章,也许可以帮助您:

http://web.archive.org/web/20110606032941/http://dev.mysql.com/tech-resources/articles/hierarchical-data.html

关于php - 列出父子树结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26311488/

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