0
這裏真的有兩個問題;爲什麼發生這種情況?對此可以做些什麼?寫入外部數組的遞歸PHP函數
對不起,這個問題很長,但大部分只是print_r
輸出!基本上,我從一個平坦的數組標籤($tags
)開始,每個標籤都有一個id
(數組索引),name
和parent_id
。然後,我遞歸地遍歷$tags
並在其父代中嵌套所有子標籤。 (見下)
它的工作原理! (見下面的輸出)。但是我遇到的問題是我的平面數組標籤是從嵌套/遞歸函數內寫入的。 (見下文)
的標籤扁平陣列:
Array
(
[1] => stdClass Object
(
[name] => instruments
[parent_id] => 0
)
[2] => stdClass Object
(
[name] => strings
[parent_id] => 1
)
[3] => stdClass Object
(
[name] => violin
[parent_id] => 2
)
[4] => stdClass Object
(
[name] => cello
[parent_id] => 2
)
[5] => stdClass Object
(
[name] => woodwind
[parent_id] => 1
)
[6] => stdClass Object
(
[name] => flute
[parent_id] => 5
)
)
這是遞歸調用函數嵌套子標籤。問題出在if
之內:我將$tag
指定爲$tree[$i]
,然後將children
屬性添加到它。這導致children
屬性被添加到$tag
。這是我想停止發生的事情。
public function tags_to_tree($tags, $parent_id = 0)
{
$tree = array();
foreach($tags as $i => $tag)
{
// add this tag node and all children (depth-first recursive)
if(intval($parent_id) === intval($tag->parent_id))
{
$tree[$i] = $tag;
$tree[$i]->children = $this->tags_to_tree($tags, $i);
}
}
return $tree;
}
嵌套的標籤輸出:
Array
(
[1] => stdClass Object
(
[name] => instruments
[parent_id] => 0
[children] => Array
(
[2] => stdClass Object
(
[name] => strings
[parent_id] => 1
[children] => Array
(
[3] => stdClass Object
(
[name] => violin
[parent_id] => 2
)
[4] => stdClass Object
(
[name] => cello
[parent_id] => 2
)
)
)
[5] => stdClass Object
(
[name] => woodwind
[parent_id] => 1
[children] => Array
(
[6] => stdClass Object
(
[name] => flute
[parent_id] => 5
)
)
)
)
)
)
添加什麼時候$tree[$i]
的children
財產,或分配到$tag
時$tree[$i]
以阻止這種情況發生,我可以做不同?
謝謝!
太神奇了!這樣一個簡單的答案這麼長的問題,非常感謝。測試和工作:) – Matthew 2011-03-12 12:04:49