2011-01-19 78 views
2

我有一个讨论的多维数组。多维数组讨论板

我正在使用递归函数(请参见下文)来回显此数组的值(注释)。但是对于我的函数,只有第一个子注释(每个数组级别)出现。

我该如何适应这个功能,以便我可以在每个数组级别回显所有子级注释,就像在正常讨论板中一样?

在此示例数组中,comment_id“4”和comment_id“7”在同一级别,但使用当前函数仅查看comment_id“4”注释。

Array 
(
    [0] => Array 
     (
      [comment_id] => 1 
      [comment_content] => This is a comment... 
      [child] => Array 
       (
        [0] => Array 
         (
          [comment_id] => 3 
          [comment_content] => This is a reply to the comment... 
          [child] => Array 
           (
            [0] => Array 
             (
              [comment_id] => 4 
              [comment_content] => This is a reply to the reply... 
              [child] => Array 
               (
               ) 
             ) 

            [1] => Array 
             (
              [comment_id] => 7 
              [comment_content] => This is a another reply to the reply... 
              [child] => Array 
               (
               ) 
             ) 
           ) 
         ) 
       ) 
     ) 

    [1] => Array 
     (
      [comment_id] => 2 
      [comment_content] => This is another comment... 
      [child] => Array 
       (
       ) 

     ) 

    [2] => Array 
     (
      [comment_id] => 6 
      [comment_content] => This is another comment... 
      [child] => Array 
       (
       ) 
     ) 
) 

我现在的功能是这样的:

function RecursiveWrite($array) { 
    foreach ($array as $vals) { 
     echo $vals['comment_content'] . "\n"; 
     RecursiveWrite($vals['child']); 
    } 
} 
+0

你可以发布你正在使用数组的例子吗? – jb1785 2011-01-19 02:02:01

+0

嗨詹妮弗,你在这里发布的代码很好。你将不得不张贴更多的代码来帮助你找到这个bug。如果评论7根本没有被打印出来,那么也许(a)你的循环里有一个“break”或“return”语句,或者(b)有一个结束整个脚本的错误。或者如果代码相当复杂,那可能是任何事情,真的。 – 2011-01-19 04:19:44

回答

0

也许我不明白你的问题,但功能似乎罚款。

我刚加垫片和COMMENT_ID到您的功能

function RecursiveWrite($array, $spacer='') { 
    foreach ($array as $vals) { 
     echo $spacer . $vals['comment_id'] . ' - ' . $vals['comment_content'] . "\n"; 
     RecursiveWrite($vals['child'], $spacer . ' '); 
    } 
} 

,并将其输出

1 - This is a comment... 
    3 - This is a reply to the comment... 
    4 - This is a reply to the reply... 
    7 - This is a another reply to the reply... 
2 - This is another comment... 
6 - This is another comment...