单表的邻接树

时间:2009-04-14 15:33:10

标签: php tree hierarchy adjacency-list

我已经阅读了很多讨论嵌套列表的人,但我想知道如何在PHP中迭代一个邻接列表/树。

我有一个表:id,title,parent_id

我已经将所有记录选择到名为$ pages的数组中。

然后使用这个php:

function makeList($pages, $used) {
    if (count($pages)) {
        echo "<ul>";
        foreach ($pages as $page) {
            echo "<li>".$page['pag_title'];
            $par_id = $page['pag_id'];
            $subsql("SELECT * FROM pages WHERE pag_parent = ".$par_id."");

            // running the new sql through an abstraction layer
            $childpages = $dbch->fetchAll();
            makeList($childpages, $used, $lastused);
            echo "</li>";
        }
        echo "</ul>";
    }
}

这种作品,但我最终会重复任何子菜单,例如

  • 首页
    • 新闻
      • 子新闻
    • 文章
      • 文章
  • 新闻
    • 子新闻
  • 文章
    • 文章
  • 子消息
  • 文章

我已经尝试将当前的id添加到一个通过该函数传递的数组中,然后使用in_array来检查它是否存在,但我没有那么高兴。

非常感谢任何帮助。

我需要解析整个树,因此选择parent为0不是一个选项

6 个答案:

答案 0 :(得分:3)

由于它已经执行了SQL,因此您无需在第一次函数调用之前在外部执行此操作。

function makeList($par_id = 0) {
    //your sql code here
    $subsql("SELECT * FROM pages WHERE pag_parent = $par_id");
    $pages = $dbch->fetchAll();

    if (count($pages)) {
        echo '<ul>';
        foreach ($pages as $page) {
            echo '<li>', $page['pag_title'];
            makeList($page['pag_id']);
            echo '</li>';
        }
        echo '</ul>';
    }
}

为了存储更多树,您可能希望查看此网站:Storing Hierarchical Data in a Database

答案 1 :(得分:3)

如果您创建按父ID分组的页面数组,则递归构建列表非常容易。这只需要一次数据库查询。

<?php

 //example data
 $items = array(
    array('id'=>1, 'title'=>'Home', 'parent_id'=>0),
    array('id'=>2, 'title'=>'News', 'parent_id'=>1),
    array('id'=>3, 'title'=>'Sub News', 'parent_id'=>2),
    array('id'=>4, 'title'=>'Articles', 'parent_id'=>0),
    array('id'=>5, 'title'=>'Article', 'parent_id'=>4),
    array('id'=>6, 'title'=>'Article2', 'parent_id'=>4)
 );

 //create new list grouped by parent id
 $itemsByParent = array();
 foreach ($items as $item) {
    if (!isset($itemsByParent[$item['parent_id']])) {
        $itemsByParent[$item['parent_id']] = array();
    }

    $itemsByParent[$item['parent_id']][] = $item;
 }

 //print list recursively 
 function printList($items, $parentId = 0) {
    echo '<ul>';
    foreach ($items[$parentId] as $item) {
        echo '<li>';
        echo $item['title'];
        $curId = $item['id'];
        //if there are children
        if (!empty($items[$curId])) {
            makeList($items, $curId);
        }           
        echo '</li>';
    }
    echo '</ul>';
 }

printList($itemsByParent);

答案 2 :(得分:1)

$ page来自哪里?如果您没有转义它或使用预准备语句,您的代码中可能会有一个SQL注入漏洞。

同样,for循环中的SELECT语句跳出来是一种不好的做法。如果表不是那么大,那么选择整个表的内容,然后遍历PHP中的结果集来构建树数据结构。在您的树作为链表的病态情况下,这可能需要最多n *(n-1)/ 2次迭代。当所有节点都已添加到树中时停止,或者从一次迭代到下一次迭代的剩余节点数保持不变 - 这意味着其余节点不是根节点的子节点。

或者,如果您的数据库支持递归SQL查询,则可以使用它,并且它只会选择父节点的子节点。您仍然需要在PHP中自己构建树对象。查询的形式如下:

WITH temptable(id, title, parent_id) AS (
  SELECT id, title, parent_id FROM pages WHERE id = ?
  UNION ALL
  SELECT a.id, a.title, a.parent_id FROM pages a, temptable t
   WHERE t.parent_id = a.id
) SELECT * FROM temptable

代替'?'在第二行有起始页面ID。

答案 3 :(得分:0)

最简单的修复就是,当你进行初始选择以设置$pages(你没有显示)时,添加一个WHERE子句,如:

WHERE pag_parent = 0

(或IS NULL,取决于您如何存储“顶级”页面)。

这样你最初不会选择所有的孩子。

答案 4 :(得分:0)

当该表变大时,递归可能变得难以处理。我写了一篇关于无递归方法的博客文章:http://www.alandelevie.com/2008/07/12/recursion-less-storage-of-hierarchical-data-in-a-relational-database/

答案 5 :(得分:0)

寻找顶级父母,所有父母和节点的所有孩子(Tom Haigh的答案的增强功能):

<?php

 //sample data (can be pulled from mysql)
 $items = array(
    array('id'=>1, 'title'=>'Home', 'parent_id'=>0),
    array('id'=>2, 'title'=>'News', 'parent_id'=>1),
    array('id'=>3, 'title'=>'Sub News', 'parent_id'=>2),
    array('id'=>4, 'title'=>'Articles', 'parent_id'=>0),
    array('id'=>5, 'title'=>'Article', 'parent_id'=>4),
    array('id'=>6, 'title'=>'Article2', 'parent_id'=>4)
 );

 //create new list grouped by parent id
 $itemsByParent = array();
 foreach ($items as $item) {
    if (!isset($itemsByParent[$item['parent_id']])) {
        $itemsByParent[$item['parent_id']] = array();
    }

    $itemsByParent[$item['parent_id']][] = $item;
 }

 //print list recursively 
 function printList($items, $parentId = 0) {
    echo '<ul>';
    foreach ($items[$parentId] as $item) {
        echo '<li>';
        echo $item['title'];
        $curId = $item['id'];
        //if there are children
        if (!empty($items[$curId])) {
            printList($items, $curId);
        }           
        echo '</li>';
    }
    echo '</ul>';
 }

printList($itemsByParent);


/***************Extra Functionality 1****************/

function findTopParent($id,$ibp){


    foreach($ibp as $parentID=>$children){ 

            foreach($children as $child){


            if($child['id']==$id){


             if($child['parent_id']!=0){

            //echo $child['parent_id'];
            return findTopParent($child['parent_id'],$ibp);

          }else{ return $child['title'];}

         }              
        }
}
}

$itemID=7;  
$TopParent= findTopParent($itemID,$itemsByParent);





/***************Extra Functionality 2****************/

function getAllParents($id,$ibp){ //full path

foreach($ibp as $parentID=>$nodes){ 

    foreach($nodes as $node){

        if($node['id']==$id){

             if($node['parent_id']!=0){

                $a=getAllParents($node['parent_id'],$ibp);
                array_push($a,$node['parent_id']);
                return $a;

              }else{
                    return array();
                  }

             }
    }
}
}


$FullPath= getAllParents(3,$itemsByParent);
print_r($FullPath);

/*
Array
(
[0] => 1
[1] => 2
)
*/

/***************Extra Functionality 3****************/

 //this function gets all offspring(subnodes); children, grand children, etc...
 function getAllDescendancy($id,$ibp){

 if(array_key_exists($id,$ibp)){

         $kids=array();
         foreach($ibp[$id] as $child){

            array_push($kids,$child['id']);

            if(array_key_exists($child['id'],$ibp))

$kids=array_merge($kids,getAllDescendancy($child['id'],$ibp));

             }

         return $kids;       

     }else{
            return array();//supplied $id has no kids
          }
 }

print_r(getAllDescendancy(1,$itemsByParent));
/*
Array
(
[0] => 2
[1] => 3
)
*/


print_r(getAllDescendancy(4,$itemsByParent));
/*
Array
(
[0] => 5
[1] => 6
)
*/


print_r(getAllDescendancy(0,$itemsByParent));
/*
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)

*/

?>