Magento 的 ORM 中的集合类最终Varien_Data_Collection
实现了IteratorAggregate
; 这就是为什么您能够以类似数组的方式(即foreach
)使用集合对象,但不能让它在for
循环中工作。一方面,d没有对对象内部元素(_items
数组成员)的直接基于键的访问——不幸的是,考虑到_items
数组的键是基于行ID的。
底线:在for
循环中处理收集项目并不是很容易,与通过IteratorAggregate
和所有相关好东西处理收集项目相比更容易。
这是两者的一个例子。如果您有直接处理集合项目的总体需求,那么您可以使用$collection->getItems()
,但再次意识到_items
数组键可能不是连续的,因为它们基于数据。另外,请注意,您需要将name
属性值添加到使用 Magento 的 EAV 模式存储的集合中:
<?php
header('Content-Type: text/plain');
include('app/Mage.php');
Mage::app();
$collection = Mage::getResourceModel('catalog/product_collection');
$collection->addAttributeToSelect('name');
//for loop - not as much fun
for ($j=0;$j<count($collection);$j++) { //count() triggers $collection->load()
$items = $collection->getItems();
$item = current($items);
echo sprintf(
"%d:\t%s\t%s\n",
$k,
$item->getSku(),
$item->getName()
);
next($items); //advance pointer
}
//foreach - a bit better
foreach ($collection as $k => $product) {
echo sprintf(
"%d:\t%s\t%s\n",
$k,
$product->getSku(),
$product->getName()
);
}
以防万一您想知道:PHP 中 FOR 与 FOREACH 的性能