我有多层父子关系,我想在树形结构中列出它们。我的表有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)
答案 0 :(得分:0)
你应该优化sql查询,而不是使用php递归。有一篇关于此的好文章,也许它可以帮到你: