1
我有mysql查詢,它將以tbl_posts的形式返回數據作爲數組。該陣列顯示如下如何從多維數組中列出父親子女關係,如果同一孩子有多個父母
$tree = array(
'C1' => 'P1',//C1 is the child of P1
'C2' => 'P1',//C2 is the child of P1
'C3' => 'P2',//C3 is the child of P1
'C4' => 'P3',//C4 is the child of P1
'GC1' => 'C1',//GC1 is the child of C1
'GC1' => 'C2',//GC1 is the child of C2
'GC2' => 'C1',//GC2 is the child of C1
'GC2' => 'C2',//GC2 is the child of C2
'GC2' => 'C4',//GC2 is the child of C4
'P1' => null,//parent post P1
'P2' => null,//parent post P2
'P3' => null,//parent post P3
);
這裏P1,P2,P3是父職位,C1,C2,C3 ..是孩子的職位和GC1,GC2他們之間的父子關係,GC3 ......是盛大孩子根據查詢返回的數組。 我想按照如下
- P1
-- C1
--- GC1
--- GC2
-- C2
--- GC1
--- GC2
- P2
-- C3
-P3
-- C4
--- GC2
的父子關係列出這些數據我已經嘗試了這種代碼如下
function parseTree($tree, $root = null) {
$return = array();
foreach($tree as $child => $parent) {
if($parent == $root) {
$return[] = array(
'parent' => $child,
'child' => parseTree($tree, $child)
);
}
}
return empty($return) ? null : $return;
}
function printTree($tree) {
if(!is_null($tree) && count($tree) > 0) {
echo '<ul>';
foreach($tree as $node) {
echo '<li>'.$node['parent'];
printTree($node['child']);
echo '</li>';
}
echo '</ul>';
}
}
$result = parseTree($tree);
echo "<pre>";
printTree($result);
,我得到的結果如下
P1
C1
C2
GC1
P2
C3
P3
C4
GC2
大孩子只被列出一次。 GC1,GC2和GC3是C1,C2和C3的子碼,但它們只列出一次。如果同一個孩子在這種情況下有多個父母,我如何列出父母親的關係?謝謝。