使用if语句外的foreach变量?

时间:2013-08-24 14:34:53

标签: php foreach

这段代码应该解释一下..

foreach($this->sections as $k => $section){ 

    $preview = array();

    foreach ($section['fields'] as $k => $type) {                               
       $preview[] = $type['type'];
    }

    if ($preview == 'header_preview'){
        echo $preview;
        // I will loop content here based on the $section loop NOT the $type loop
    }

}

我只需要将每个$section['fields']放在该循环之外,然后再获取所有$section['fields']的列表,然后使用其中一个字段类型创建if语句。以上是不工作的,我将在这里向您展示工作代码。

foreach($this->sections as $k => $section){ 

    foreach ($section['fields'] as $k => $type) {                               
        if ($type['type'] == 'header_preview'){
           //I work but im in a nested loop I need out
        }
     }

  //The main loop here.. the above loop is just to setup data to use inside this loop? Make sense? I hope!

}

我希望这是有道理的......

var_dump的片段$this->sections

array(26) { ["general"]=> array(3) { ["title"]=> string(7) "General" ["icon"]=>    string(106) "img/icons/sub.png" ["fields"]=> array(5) { [0]=> array(6) { ["id"]=>    string(10) "responsive" ["type"]=> string(6) "switch" ["title"]=> string(35) "Responsive" ["desc"]=> string(10) "Responsive" ["options"]=> array(2) { [1]=> string(2) "On"    [0]=> string(3) "Off" }

3 个答案:

答案 0 :(得分:1)

有可能$ k已被复制,因此循环不知道该怎么做。您可以尝试将$ k更改为$ x,看看它是否有效。

foreach($this->sections as $k => $section){ 

    $preview = array();

    foreach ($section['fields'] as $x => $type) {                               
       $preview[] = $type['type'];
    }

    foreach($preview as $elem){
        if ($elem == 'header_preview'){
            echo($elem);
        }
    }
}

答案 1 :(得分:1)

嗯......也许

foreach($this->sections as $k => $section){ 

    $preview = array();

    foreach ($section['fields'] as $x => $type) {                               
       $preview[] = $type['type'];
    }

    if(!in_array('header_preview', $preview)){

        // Here $preview DOES NOT contain 'header_preview'
        // Do stuff

    } 
}

答案 2 :(得分:1)

$header_preview=false;
foreach($this->sections as $k => $section){ 
    $header_preview=false;// reset the var $header_preview
    foreach ($section['fields'] as $k => $type) {                               
        if ($type['type'] == 'header_preview') $header_preview = true;
    }
    if($header_preview==true){
        //here you can add or extract from this array that has `header_preview` value for one of it's field type
    }
}