2012-07-20 113 views
5

爲什麼這個for循環可以獨立處理每個條件,但是第一個條件一起並不重要?for循環中的兩個條件

for ($j = 0; $j < 5 or $j < $synCount; $j++) 

我只想循環運行5次

如果synCount低於此。

回答

12

您可能的意思是「$j unde的R 5 $sysCount下」$j,或:

$j < min(5, $sysCount) 
+0

不知道這個功能。比我的解決方案更優雅,不錯! – hellsgate 2012-07-20 11:41:52

+0

可愛!非常感謝。 – flux 2012-07-20 11:47:57

0

可以憂色的break聲明離開for循環:

for ($j = 0; $j < 5 ; $j++) 
{ 
    if($j >= $synCount) 
     break; 
    //treatment 
} 

或者循環之前計算出你的極限:

$ max = $synCount < 5 ? $synCount : 5; 
for ($j = 0; $j < $synCount ; $j++) 
{ 
    //treatment 
} 

另一種解決方案,快捷:採用min()

for ($j = 0; $j < min(5, $synCount) ; $j++) 
{ 
    //treatment 
} 
0

嘗試這樣的:

$loopcount = ($syncount < 5) ? $syncount : 5; 
for ($j = 0; $j < $loopcount; ++$j) { 
} 

第一行決定是否$syncount小於5或不然後分配一個值以$loopcount爲基礎。然後循環運行所需的次數。

0
for ($j = 0; $j < ($syncCount <= 5 ? $syncCount : 5); $j++) 

或略微優化(但我想用5個或更少的迭代這個絕對無所謂)

for ($j = 0, $limit = min($syncCount, 5); $j < $limit; $j++) 

Anothe不錯的解決方案

foreach (range(0, min($syncCount, 5)) as $j) 

旁註

$syncCount <= 5 ? $syncCount : 5 == min($syncCount, 5) 
2

很簡單

$j < min(5, $sysCount) 
0
$productsprice=ProductPrice::model()->findAllByAttributes(array ('product_id'=>$products_data->product_id)); 
foreach($productsprice AS $productsprice): 
    for($quantity = 0; $quantity <= 10; $quantity++) 
    { 
     echo '<li >'.array(value=>'ProductPrice::model()->getquantity($data->quantity)').'</li>' ; 
    } 
endforeach; 
+1

請添加一些關於您的答案的細節。 – emmanuel 2015-02-24 12:58:38