2017-08-24 22 views
0

我有PHP代碼:PHP的foreach回聲X元素和計數的許多元素如何離開

if($stmt->rowCount() > 0) : 
    $otherProfiles = array(); 
    foreach($playerOtherProfiles as $otherProfile) : 
     $otherProfiles[] = "<li>$otherProfile[Name]</li>"; 
    endforeach; 

    //echo implode(", ", $otherProfiles).. 

這將打印all otherProfiles。是否可以只打印,然後打印多少個左側面?

例如,如果配置文件是4 - 印刷3和回聲1分左,

如果5 - 打印3,回聲2左側..由於預先

回答

2
if($stmt->rowCount() > 0) : 
    $otherProfiles = array(); 
    $i = 0; 
    $left = 0; 
    foreach($playerOtherProfiles as $otherProfile) { 
     if ($i==3){ 
     $left++; 
     } 
     else{ 
     $otherProfiles[] = "<li>$otherProfile[Name]</li>"; 
     $i++;} 
     } 
    echo $left . "left"; 
    endforeach; 
+1

非常感謝你! – EvaldasL

1

只需使用增量變量

$total_row=$stmt->rowCount(); 
$i=0; 
foreach($playerOtherProfiles as $otherProfile) : 
    if($i<3){ 
    $otherProfiles[] = "<li>$otherProfile[Name]</li>"; 
    $i++; 
    }else{ break; } 
endforeach; 
echo "Left - :".$toal_row-$i; 
+0

謝謝! ;)) – EvaldasL