0

我确定答案遍布整个网络,但我不确定搜索此问题的正确方法。

foreach ($sections as $key => $inside) {

      foreach ($inside['fields'] as $key => $field) {

          echo '<li>'.var_dump ($field['type']).'</li>';

      }

}

这会转储字符串列表。

string(6) "switch"
string(6) "switch"
string(4) "text"
string(4) "text"
string(8) "textarea"
string(6) "switch"
string(9) "radio_img"
string(9) "radio_img"
string(10) "multi_text" 

我想再添加一个 foreach ,即 foreach "switch" 或上述字符串列表中所需的任何字符串。

所以像

foreach ($sections as $key => $inside) {

      foreach ($inside['fields'] as $key => $field) {

            foreach ($field['type']['switch'] as $string) {

                //Loop through all switches 

            }

      }

}

这对我来说是新的,我无法通过谷歌找到答案,不知道如何指定一个字符串值并迭代每个值。

操作:

foreach ($sections as $key => $inside) {
    foreach ($inside['fields'] as $key => $field) {
        if($field['type'] == 'switch') {
            echo '<div class="'.$field['id'].'-stackoverflow">mycontent</div>';
        } 
    }
}

这将输出类似

<div id="main-stackoverflow">mycontent</div>
<div id="layout-stackoverflow">mycontent</div>
<div id="colors-stackoverflow">mycontent</div>
<div id="fonts-stackoverflow">mycontent</div>

然后,我将使用jQuery在适当的页面中显示适当的div,这是一个选项面板,并且在选择主选项时,将有一个选项,然后将看到主堆股div。这只是一个粗略的描述。谢谢大家的帮助,我希望我不必问这么简单的问题,这个想法一直在我脑海中,但很高兴得到其他人的意见。

4

4 回答 4

4

不需要第三个。foreach试试像

foreach ($sections as $key => $inside) {

    foreach ($inside['fields'] as $key => $field) {
        if($field['type'] == 'switch') {
            echo $filed['type'];
            // Or even increment an counter to display how many times it occurs
            // DO $new_arr[] = $field['type']['switch'];
        } 
    }

}
于 2013-08-24T07:22:10.183 回答
1

使用 switch 而不是另一个 foreach

foreach ($sections as $key => $inside) {
    foreach ($inside['fields'] as $key => $field) {
       switch ($field['type'])
       {
           case "switch":
               //do something
               break;
           case "textarea":
               //do something
               break;
           case "multi_text":
               //do something
               break;
           // add other cases...
       }
    }
}
于 2013-08-24T07:24:47.830 回答
0

你想通过遍历字符串来实现什么?

您可以计算它们并执行 for 循环。

foreach ($sections as $key => $inside) {

  foreach ($inside['fields'] as $key => $field) {

        foreach ($field['type']['switch'] as $string) {

            if($string == "switch"){
                $switch_counter++;
            }
            // ...

        }
        for($i=0; $i<$switch_counter, $i++) {
            // do something
        }

  }

}

于 2013-08-24T07:26:10.747 回答
0

试试这个:

$controls = array();
foreach ($sections as $key => $inside) {
    foreach ($inside['fields'] as $key => $field) {
       $controls[$field['type']][] = $field;
    }    
}

var_dump($controls);
于 2013-08-24T07:27:54.883 回答