doujiao7679 2011-09-13 02:35
浏览 31
已采纳

在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 08: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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog