2011-03-12 47 views
0

這裏真的有兩個問題;爲什麼發生這種情況?對此可以做些什麼?寫入外部數組的遞歸PHP函數

對不起,這個問題很長,但大部分只是print_r輸出!基本上,我從一個平坦的數組標籤($tags)開始,每個標籤都有一個id(數組索引),nameparent_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]以阻止這種情況發生,我可以做不同?

謝謝!

回答

2

平面數組是對象(引用)的數組,即使將對象放入新數組中,它仍然是您正在移動的同一對象。

如果不希望被編輯同一個參考,看看Object Cloning

即使用:

$tree[$i] = clone $tag; 
+0

太神奇了!這樣一個簡單的答案這麼長的問題,非常感謝。測試和工作:) – Matthew 2011-03-12 12:04:49