2013-09-24 61 views
3

有沒有在PHP中爲foreach方程添加where類的方法。PHP Foreach,其中

此刻我正在添加一個如果像這樣的foreach。

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


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

推測PHP必須遍歷所有這些結果。有沒有更有效的方式來做到這一點。像

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

東西可以這樣做

+1

你可以在foreach循環之前過濾數組,所以首先過濾'headcontent',然後循環。但我認爲你從中獲益不多。 – djot

+0

你每次都運行兩個循環嗎?在這些'if'語句中我們討論了多少代碼?這兩種情況下的內容是相似還是完全不同? – insertusernamehere

+0

有沒有這樣的事情,「foreach方程」... – Virus721

回答

1

使用SWITCH聲明。

<?php 
    foreach($themes as $theme) 
     { 
     switch($theme['section']) 
     { 
      case 'headcontent': 
       //do something 
       break; 
      case 'main content': 
       //do something 
       break; 
     } 
     } 
    ?> 
0

你最好使用for loop對於像

<?php 
    $cnt = count($themes); 
    for($i = 0;$i < $cnt,$themes[$i]['section'] == 'headcontent' ;$i++){ 

    } 
?> 
+0

爲什麼?另外使用foreach參考...收益? – djot

+0

帶參考..怎麼會 – Gautam3164

+0

爲什麼你用for循環代替? ...'foreach($ themes爲&$ theme)':至少要避免將數組「複製」到內存中,並且應該幾乎與for循環一樣快。但是你的「方式」看起來也很酷;)[據我所知'==='比'=='快] – djot

8

A「的foreach,其中」將是完全一樣的「的foreach假設」,因爲反正PHP 遍歷所有項目檢查條件。

你可以把它寫在一行,以反映「其中」精神:

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

這將成爲真正爲構建建議在問題結束相同;你可以用同樣的方式閱讀/理解它。

但是,它並沒有解決這樣一個事實,即在問題的具體情景中,使用任何種類的「foreach-where」構造都會多次遍歷所有項目。答案就在於將所有的測試和相應的治療重新組合到一個循環中。

+0

這是我的問題的完美答案,謝謝。 – darkbluesun

+0

儘管我的PHP代碼linter完全不喜歡這個。 – darkbluesun