【问题标题】:List Parent Child tree structure列出父子树结构
【发布时间】:2014-10-11 13:45:54
【问题描述】:

我有多层父子关系,我想在树结构中列出它们。我有带有 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)

【问题讨论】:

  • 尝试增加内存限制:ini_set('memory_limit', '128M');
  • 我认为这不是解决方案,因为我已经改变了它。
  • 那么你必须优化你的脚本:)
  • 互联网搜索返回的链接:'php mysql generate menu'可能有用。

标签: php mysql


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2015-04-26
    • 1970-01-01
    • 2012-03-11
    • 2015-03-02
    • 2014-07-04
    • 1970-01-01
    • 2013-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多