用于邻接列表显示的递归PHP函数

时间:2010-11-22 04:27:06

标签: php recursion hierarchical-data adjacency-list

我有一个像这样的数据库:

id  text           parent
1   Parent 1        0   
2   Child of 1      1   
3   Sibling         1   
4   Another Parent  0 
5   A first child   4

所以我试图抓住一个树形结构,列出父母。我知道另一个选项(我认为是嵌套的吗?)但是我现在要坚持这个。我现在正试图将数据从数据库中取出并放入PHP中的嵌套数组结构中。我有这样的功能:

class Data_Manager
{   
    public $connection = '';
    public $collection = array();

    function __construct() {
        $this->connection = mysql_connect('localhost', 'root', 'root');
        $thisTable = mysql_select_db('data');
            // error handling truncated
    }


    function get_all() {
        $arr = &$this->collection;

        $this->recurseTree('', 0, $arr);
        var_dump($arr);
    }

    function recurseTree($parent, $level, $arrayNode) {
        $result = mysql_query('SELECT * FROM tasks WHERE parent="' . $parent . '";');

        while ($row = mysql_fetch_array($result)) {
            $row['children'] = array(); //where I'd like to put the kids    
            $arrayNode[$row['id']]= $row;
            $this->recurseTree($row['id'], $level+1, $arrayNode[$row['id']]);
        }
    }
}

所以我想提出的是某种关联数组的嵌套树,但我无法弄清楚如何做到这一点。似乎没有什么东西可以写入我传入的数组中,而且我在递归中有点失去了对自己的追踪。任何人都可以帮助我完成最后一次驼峰,这将导致像:

[
Parent1 => [
               children => ['Child of 1', 'Sibling']
           ],
AnotherParent => [
                     children => ['First Child']
                 ]
]

我不太关心输出的具体形式。它将变成JSON,我还没有处理编写客户端处理程序,所以不用担心确切的结构。

谢谢!

4 个答案:

答案 0 :(得分:5)

试试这个。

$sql = "SELECT * FROM tasks";
$r = mysql_query($sql, $conn);
$arr = array();
while ($row = mysql_fetch_assoc($r))
   $arr[] = $row

function build($arrayIn, $parent)
{
    $makeFilter = function($p) {return function($x) use ($p) {return $x['parent'] == $p;};};
    $f = $makeFilter($parent);
    $these = array_filter($arrayIn, $f);
    $remaining = array_diff_assoc($arrayIn, $these);
    $ans = array();

    foreach($these as $cur)
    {
       $ans[$cur['text']] = build($remaining, $cur['id']);
    }
    return $ans ? $ans : null;
}

$tree = build($arr, 0)
echo_r($arr);
echo "becomes<br />";
echo_r($tree);

这是我的输出:

Array
(
[0] => Array
    (
        [text] => a
        [id] => 1
        [parent] => 0
    )

[1] => Array
    (
        [text] => b
        [id] => 2
        [parent] => 0
    )

[2] => Array
    (
        [text] => c
        [id] => 3
        [parent] => 1
    )

[3] => Array
    (
        [text] => d
        [id] => 4
        [parent] => 2
    )

[4] => Array
    (
        [text] => e
        [id] => 5
        [parent] => 2
    )

[5] => Array
    (
        [text] => f
        [id] => 6
        [parent] => 3
    )

)

becomes

Array
(
[a] => Array
    (
        [c] => Array
            (
                [f] => 
            )

    )

[b] => Array
    (
        [d] => 
        [e] => 
    )

)

答案 1 :(得分:0)

这段伪代码应该有所帮助。

function getTasks($parent = 0){
    $tasks = array();
    $query = mysql_query("select * from table where parent = $parent");
    $rows = array();
    while(($row = mysql_fetch_assoc($query)) !== FALSE){ $rows[] = $row; }
    if(count($rows)){
        $tasks[$parent][] = getTasks($parent);
    } else {
        return $tasks;
    }
}

$tasks = getTasks();

答案 2 :(得分:0)

这里你真的不需要递归函数。使用一个数据库查询获取所有数据并循环遍历它。它会比多个数据库调用快得多。

假设您将数据存储在MySQL see the answer to this question for instructions on how to write a SELECT statement against an Adjacency List table that returns everything in a hierarchy中。简而言之,使用MySQL会话变量。然后取结果集并循环遍历它,使用堆栈推送 - 弹出 - 查看最后一个父ID以确定数据结构的缩进。

答案 3 :(得分:0)

这是我为处理各种邻接列表任务而编写的PHP类。

http://www.pdvictor.com/?sv=&category=just+code&title=adjacency+model