PHP Foreach,Where

Rob*_*ght 4 php foreach loops where

有没有办法在PHP中为foreach方程添加where类.

目前我正在向这样的foreach添加一个if.

<?php foreach($themes as $theme){
    if($theme['section'] == 'headcontent'){
       //Something
    }
}?>


<?php foreach($themes as $theme){
    if($theme['section'] == 'main content'){
       //Something
    }
}?>
Run Code Online (Sandbox Code Playgroud)

据推测,PHP必须遍历每个结果的所有结果.有没有更有效的方法来做到这一点.就像是

foreach($themes as $theme where $theme['section'] == 'headcontent')

可以做到这一点

Soc*_*cce 10

"foreach-where"与"foreach-if"完全相同,因为无论如何PHP 必须循环遍历所有项目以检查条件.

你可以把它写在一行上以反映"在哪里"的精神:

foreach ($themes as $theme) if ($theme['section'] == 'headcontent') {
    // Something
}
Run Code Online (Sandbox Code Playgroud)

这与问题末尾提出的结构非常相似; 你可以用同样的方式阅读/理解它.

然而,它没有解决这样一个事实:在问题的具体情况中,使用任何类型的"foreach-where"结构实际上会循环遍历所有项目几次.答案就在于将所有测试和相应的处理重新组合成一个循环.