簡體   English   中英

遞歸PHP函數,用於顯示鄰接表

[英]Recursive PHP function for adjacency-list display

我有一個這樣的數據庫:

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,並且我還沒有編寫客戶端處理程序,因此不必擔心確切的結構。

謝謝!

嘗試這個。

$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] => 
    )

)

這是我編寫的用於處理各種鄰接列表任務的PHP類。

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

這一點偽代碼應該會有所幫助。

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();

您實際上不需要這里的遞歸函數。 使用一個數據庫查詢獲取所有數據並對其進行循環。 這將比多個數據庫調用要快得多。

假設您將數據存儲在MySQL中, 請參見此問題的答案,以獲取有關如何針對將返回層次結構中所有內容的“鄰接表”表編寫SELECT語句的說明 簡而言之,請使用MySQL會話變量。 然后獲取結果集並對其進行循環,使用堆棧推送-彈出-窺視最后一個父ID以確定數據結構的縮進。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM