简体   繁体   English

在PHP 5.4.x中定义自定义迭代器?

[英]Define a Custom Iterator in PHP 5.4.x?

Does PHP (5.4.x) allow one to create custom iterators that can be dropped into foreach loops ? PHP(5.4.x)是否允许一个创建可放入foreach循环的自定义迭代器? (I have seen an iterator example that was fairly clunky) (我看过一个很笨拙的迭代器示例)

I am accessing a web API that only allows one to pull N rows/objects per call, which results in clunky local code - ie an outer loop for grabbing a batch of data from the API and an inner loop for processing the elements of each batch. 我正在访问一个Web API,该Web API每次调用只能拉出N行/对象,这会导致笨拙的本地代码-即用于从API抓取一批数据的外循环和用于处理每批元素的内循环。

I would prefer to push the outer loop into an iterator (that pulls down blocks of data and keeps track of the index into the external API etc) so I can write code more like this: 我更喜欢将外部循环推入迭代器(下拉数据块并跟踪到外部API的索引等),这样我可以编写如下代码:

$datastream = new ApiIterator(/*params here*/);
foreach($datastream as $row){
   // do inner loop processing here
}

Thanks! 谢谢!

从PHP 5.0开始,您可能需要使用PHP的Class Iterator接口( http://php.net/manual/en/class.iterator.php )并在ApiIterator Class中对其进行扩展(实现)

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

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