Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Collection classes in Magento's ORM ultimately subclass <a href="https://github.com/benmarks/magento-mirror/blob/magento-1.7/lib/Varien/Data/Collection.php#L34" rel="nofollow noreferrer"><code>Varien_Data_Collection</code></a> which implements <code>IteratorAggregate</code>; this is why you are able to work with the collection object in an array-like fashion (i.e. <code>foreach</code>), but not have it work for the <code>for</code> loop. For one thing, dThere is no direct key-based access to the elements inside the object (<code>_items</code> array members) - unfortunate, given that the key for the <code>_items</code> array is based on the row ID.</p> <p>Bottom line: working with collection items in a <code>for</code> loop is not very easy, not when compared to the ease of working with collection items via <code>IteratorAggregate</code> and all of its related goodies.</p> <p>Here's an example of both. If you have an overarching need to work with the collection's items directly then you can use <code>$collection-&gt;getItems()</code>, but again realize that the <code>_items</code> array keys may not be sequential as they are based on the data. Also, note that you need to add the <code>name</code> attribute value to collections stored using Magento's EAV pattern:</p> <pre><code>&lt;?php header('Content-Type: text/plain'); include('app/Mage.php'); Mage::app(); $collection = Mage::getResourceModel('catalog/product_collection'); $collection-&gt;addAttributeToSelect('name'); //for loop - not as much fun for ($j=0;$j&lt;count($collection);$j++) { //count() triggers $collection-&gt;load() $items = $collection-&gt;getItems(); $item = current($items); echo sprintf( "%d:\t%s\t%s\n", $k, $item-&gt;getSku(), $item-&gt;getName() ); next($items); //advance pointer } //foreach - a bit better foreach ($collection as $k =&gt; $product) { echo sprintf( "%d:\t%s\t%s\n", $k, $product-&gt;getSku(), $product-&gt;getName() ); } </code></pre> <p>And just in case you are wondering: <a href="https://stackoverflow.com/questions/3430194/performance-of-for-vs-foreach-in-php">Performance of FOR vs FOREACH in PHP</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload