doujiao7679 2011-09-12 18:35
浏览 32
已采纳

在PHP中使用父项和子项(按类别)对查询进行排序

I have a SQLite DB with a table called "library" containing 3 fields (12php sMb)

Id (unique identifier) // libraryName, containing a string // parentLibId, containing the ID of the parent Library.

If the library is in the "root", parentLibId is Null (empty)

I need an array that will return a tree with parents and child starting from the root.

Anyone know how to do that without too many code?

$dbh = new PDO('sqlite:my.sqlite') or die("Error 0xDB0001");
$sth = $dbh->prepare("SELECT * FROM library");
$sth->execute();
$result = $sth->fetchAll();

I have a time processing page limit given by my friend as a little competition and this part I cannot figure it out, I used a code but it's so long, I feel stupid XD

Any help is welcomed, if I'm unclear, just say it and I'll give more details.

Thank you very much your help is appreciated!!

Have a good evening all!

  • 写回答

1条回答 默认 最新

  • dpntq48842 2011-09-13 00:50
    关注

    this function is not tested. This is main idea.

    getTree();
    
    function getTree($child = null)
    {
        $dbh = new PDO('sqlite:my.sqlite') or die("Error 0xDB0001");
    
        //It's just example. Security and best practice is your problem :p
        if ($child)
            $where = 'parentLibId = ' . $child;
        else
            $where = 'parentLibId IS NULL ';
    
        $sth = $dbh->prepare("SELECT * FROM library" . $where);
        $sth->execute();
    
        if ($child)
        {
            $result = $sth->fetchAll()
            $return = $result;
        }else{ //get parents
            while ($result = $sth->fetch())
            {
                //one by one
                $return[] = array(  'parent' => $result, //parent info
                                    'childs' => getTree($result['id']) //childs
                                );
            }
        }
    
        return $return;
    }
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部