限制循环在 php 中运行的次数

2021-12-26 00:00:00 foreach php

我有一个 foreach 循环,我需要将其限制为前 10 个项目,然后中断它.

I have a foreach loop that i need to limit to the first 10 items then break out of it.

我在这里怎么做?

foreach ($butters->users->user as $user) {
    $id = $user->id;
    $name = $user->screen_name;
    $profimg = $user->profile_image_url;
    echo "things";    
} 

也希望得到详细的解释.

Would appreciate a detailed explanation as well.

推荐答案

如果要使用foreach,可以添加一个额外的变量来控制迭代次数.例如:

If you want to use foreach, you can add an additional variable to control the number of iterations. For example:

$i=0;
foreach ($butters->users->user as $user) {
    if($i==10) break;
    $id = $user->id;
    $name = $user->screen_name;
    $profimg = $user->profile_image_url;
    echo "things";  
    $i++;  
} 

相关文章