Php 如何限制for循环中的项目?

Php 如何限制for循环中的项目?,php,for-loop,count,limit,Php,For Loop,Count,Limit,如何限制for循环中的项目 <?php for ($i=0; $i< count($contentdinamit["chart"]["songs"]["song"]); $i++ ) { echo'<li class="up"><a href="' .$contentdinamit["chart"]["songs"]["song"]["$i"]["artist_name"].'"&g

如何限制for循环中的项目

<?php               
     for ($i=0; $i< count($contentdinamit["chart"]["songs"]["song"]); $i++ ) {
         echo'<li class="up"><a href="'
             .$contentdinamit["chart"]["songs"]["song"]["$i"]["artist_name"].'"><strong>'
             .$contentdinamit["chart"]["songs"]["song"]["$i"]["song_name"].'</strong></a><br /><a href="'
             .$contentdinamit["chart"]["songs"]["song"]["$i"]["artist_name"].'">'
             .$contentdinamit["chart"]["songs"]["song"]["$i"]["artist_name"].'</a></li>';
    }
 ?>

将其限制为20项。试一试

$limit = min(20, count($contentdinamit["chart"]["songs"]["song"]));
for ($i=0; $i < $limit; $i++ )
$limit=min(20,计数($contentdinamit[“图表”][“歌曲”][“歌曲]));
对于($i=0;$i<$limit;$i++)

你的意思是限制输出?只需将for循环调整为只回显所需的条目,而不是在达到数组计数之前循环。假设您只需要5件物品,然后执行以下操作:

$maximum = 5; // Set whatever number you want here as a maximum, and then...
for($i = 1;$i <= $maximum;$i++) {
    // Echo goes here
}
$maximum=5;//在这里设置您想要的最大值,然后。。。

对于($i=1;$i如果您觉得代码产生的输出太多,请在循环中执行以下操作:

if($i > 10)// 10 is your limit.
     break;

将($i=0;$i的循环限制设置为10,我不知道你的意思。但以下是我从你的问题中理解的

<?php     

     for ($i=0; $i< count($contentdinamit["chart"]["songs"]["song"]); $i++ ) {

     if(($i+1)<=10){//limit your item by 10
         echo'<li class="up"><a href="'
             .$contentdinamit["chart"]["songs"]["song"]["$i"]["artist_name"].'"><strong>'
             .$contentdinamit["chart"]["songs"]["song"]["$i"]["song_name"].'</strong></a><br /><a href="'
             .$contentdinamit["chart"]["songs"]["song"]["$i"]["artist_name"].'">'
             .$contentdinamit["chart"]["songs"]["song"]["$i"]["artist_name"].'</a></li>';
    }
}
 ?>

如果您只需要n个条目,那么使用

select * from table_name limit $max;

请解释一下。您想做什么???//将($i=0;$i)的循环限制设置为10,您不应该在for声明中计数()。在$count=count(…)之外计数,并像这样使用它$i@djot我比你投了更高的票,但现在我认为这并不重要
不会花太多时间。@PiTheNumber:所以用你的话说,这就是微优化;)…但为什么不进行许多微优化呢?这在foreach循环中很有用,但在for循环中,您可以将停止条件设置为第二个参数。@PiTheNumber:我并没有说这个答案是错误的,如果您在for循环参数中设置相同的条件,则效率不高。这只是多余的代码行。@Olds这是一种糟糕的风格。
if($i>10)
这将在第11项停止?为什么要循环所有内容?为什么是第二个计数器?很抱歉,我已经更改了它。我的错误:PIf计数是100万,这将永远需要。如果你插入Lucifer Orichalcum这样的中断,这是一种不好的样式。你怎么能说这是一种不好的样式?中断一般来说不是不好的样式。如果它使代码的可读性不如goto命令,因此您应该只在需要时使用它。更多关于这一点的信息并不能解决它。您必须使用min(),请参阅“不理解为什么这被否决”。我认为这是一个很好的答案。但我更喜欢使用
if($I+1)这个好主意。如果OP使用mysql,这将是一个好办法。
select * from table_name limit $max;