Magento:迭代Varien Object集合的正确方法

时间:2013-01-24 14:53:04

标签: magento object collections magento-1.7

如果我要创建一个collection来检索属于products的所有category并使用给定的ID,请执行以下操作:

    $storeId    = Mage::app()->getStore()->getId();  
    $product    = Mage::getModel('catalog/product');  
    $category   = Mage::getModel('catalog/category')->load(39);
    $catName    = $category->getName();

    $visibility = array(  
        Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH,  
        Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG  
    );  

    $products = $product->setStoreId($storeId)  
        ->getCollection()  
        ->addAttributeToFilter('visibility', $visibility)  
        ->addCategoryFilter($category)  
        ->addAttributeToSelect(array('name'), 'inner')
        ->setOrder('name', 'asc')
    ;  

    $collection = $products;  

如何迭代集合并访问每个项目的数据,在这种情况下,项目是产品。

我本来期望像下面这样给我每个项目的可用数据,但似乎不起作用:

    foreach ($collection as $key => $value) {
        var_dump($value->getData());
    }

1 个答案:

答案 0 :(得分:5)

你很亲密。尝试做

foreach ($collection as $obj) {
        echo $obj->getName();
}