简体   繁体   English

遍历PHP“对象” x次?

[英]Loop through PHP “Object” x amount of times?

I need to be able to loop through a PHP object about 25 times, but using a foreach with an iteration counter doesn't get the job done. 我需要能够遍历PHP对象约25次,但是将foreach与迭代计数器结合使用并不能完成工作。 Can someone advise please? 有人可以建议吗?

Things I've Tried 我尝试过的事情

$i = 0;

foreach($items as $item){
    if($i < 25){
        //do code here
    $i++;
    }else{
        break;
    }
}

this successfully counts through 1-25 and break but my code does not execute it just stops completely. 这成功地通过1-25计数并中断,但是我的代码没有执行,只是完全停止了。

and i've also tried using a for loop but again this doesn't work. 而且我也尝试过使用for循环,但这再次不起作用。 So what i really want to know is if there is a way to loop through a PHP object X amount of times before breaking out of the loop and carrying on with my code. 所以我真正想知道的是,是否有一种方法可以在中断循环并继续执行我的代码之前,在X对象中循环浏览X次。

The reason i need this is because if i use "foreach" without limiting it, it will go through about 300 times which is way too much. 我需要这个的原因是因为如果我不限制使用“ foreach”,它将经历大约300次,这太多了。

If iterating through whole collection is "way too much" maybe do not fetch all items from wherever they come from or slice the input 如果遍历整个集合“太多了”,则可能不要从它们来自何处获取所有项目或对输入进行切片

foreach (array_slice($items, 0, 25) as $item) {
     // do code here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM