php中的Foreach字符串?

时间:2013-08-24 07:18:59

标签: php

我确定答案是在网上,但我不确定搜索这个的正确方法。

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,它是一个选项面板,并且隐藏了选项,当选择main选项时,main-stackoverflow div将是可见的。这只是一个粗略的描述..感谢各位帮忙,我希望我不要问这么简单的问题这个想法一直在我脑海中,但是让别人输入很好。

4 个答案:

答案 0 :(得分: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'];
        } 
    }

}

答案 1 :(得分:1)

使用开关代替另一个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...
       }
    }
}

答案 2 :(得分: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
        }

  }

}

答案 3 :(得分:0)

试试这个:

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

var_dump($controls);