2016-07-14 73 views
0

我有这个数组(见下文),我想重复每个数组有一个键“重复”与代表多少次重复的值。在数组中重复显示:重复输出该元素

$fields = array(
    array(
     'type' => 'title-wrap', 
     'holder' => 'h4', 
     'heading' => 'Test heading', 
    ), 
    array(
     'repeat' => 3, 
     'type' => 'radio', 
     'name' => 'specific_name', 
     'value' => array(
      0 => 'First', // value for first repeat 
      1 => 'Second', // value for second repeat 
      2 => 'Third' // value for third repeat 
     ), 
    ) 
); 

对于我创建generateForm名为递归函数:

function generateForm($fields, $index = 0) { 
    if ($fields == '') { return false; } 
    foreach ($fields as $field) { 
     if (isset($field['type'])) { 
      switch ($field['type']) { 
      case 'title-wrap': 
       echo $field['heading']; 
       break; 
      case 'radio': 
       echo $field['value'][$index]; 
       break; 
      } 
     } 
     if (isset($field['repeat'])) { 
      for ($i=0; $i < $field['repeat']-1; $i++) { 
       generateForm($field, $i); 
      } 
     } 
    } 
} 

输出我想:

测试标题
首先

但我没有得到输出中的最后两个单词。我究竟做错了什么?

+0

能否downvoter请小心发表评论。 – Oli

回答

1

如果你想坚持用递归方法,那么你就需要纠正一些问题:

  • 你拥有的递归调用并不传递一个数组,而是一个数组的元素。然而这个函数需要一个数组。所以你应该在传递第一个参数时将其包装在数组结构中:[$field]
  • 一旦上述内容得到修复,当您在递归调用中时,对重复键的测试将再次成功,因此您将再次启动该循环,并进入无限递归。为了防止这种情况发生,请不要循环,但是如果至少还有一个要继续,则可以递归地调用函数进行下一次重复。

以下是更正代码:

function generateForm($fields, $index = 0) { 
    if ($fields == '') { return false; } 
    foreach ($fields as $field) { 
     if (isset($field['type'])) { 
      switch ($field['type']) { 
      case 'title-wrap': 
       echo $field['heading'] . "\n"; 
       break; 
      case 'radio': 
       echo $field['value'][$index] . "\n"; 
       break; 
      } 
     } 
     if (isset($field['repeat']) && $index < $field['repeat'] - 1) { 
      generateForm([$field], $index + 1); 
     } 
    } 
}