2017-08-24 71 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