限制数组中显示的结果数

时间:2013-06-26 09:35:41

标签: php arrays foreach do-while

我有一个数组,我只使用foreach语句循环,我只想显示前5个结果。这是最初的foreach声明:

<?php    
foreach ( $scorersCount as $player => $goals) {

$playerinfo = get_userdata($player);
$playerteam = get_user_meta($player, 'team-meta');
$teamname = get_post($playerteam[0]);
$playername = $playerinfo->user_login;

?>
<tr>
       <td class="playername"><?php echo $playername ?></td>

       <td class="teamname"><?php echo $teamname->post_title ?></td>

       <td><?php echo $goals ?></td>
    </tr>

<?php } > //end foreach

我认为我需要在$i <= 5的foreach中包含while语句或while while stement但是当我尝试这样做时,我得到第一个结果5次而不是前5个结果。有人可以告诉我如何正确地做到这一点吗?

2 个答案:

答案 0 :(得分:1)

您可以break foreach循环处理所需的条件,例如

<?php  $index=0;   
foreach ( $scorersCount as $player => $goals) {

$playerinfo = get_userdata($player);
$playerteam = get_user_meta($player, 'team-meta');
$teamname = get_post($playerteam[0]);
$playername = $playerinfo->user_login;

?>
<tr>
       <td class="playername"><?php echo $playername ?></td>

       <td class="teamname"><?php echo $teamname->post_title ?></td>

       <td><?php echo $goals ?></td>
    </tr>

<?php $index++;
 if($index=== 5) {
        break;    
    }
 } ?> 

答案 1 :(得分:0)

您也可以使用array_chunk

$scorersCount = array_chunk($scorersCount,5,true);
foreach ( $scorersCount[0] as $player => $goals) {