Magento 1.9 – How to Get Array of Size and Quantity from Product Collection

magento-1.9PHP

I am quite a new to magento, but trying hard to learn it and know all it models and collections.
I had a requirement to get the size of all the simple products and its quantity. We do have the size attribute set and many product are of type configurable and we are displaying that on the list page as well.

Configurable product do have the quantity and size as it is associates all the simple products.

Now i am really curious to know the stock in this format.

stock ={
"size" => "quantity"
 }

where size is the attribute and it can be x,xl,xs,xxl,xxxl and so on. and quantity is the quantity which is in stock for that particular size.

What i have tried uptill now is to get the name,id,sku,product url, images url and category id as well.

$collection = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('*');
// set the offset (useful for pagination)

// we iterate through the list of products to get attribute values
foreach ($collection as $product) {
  echo $product->getName(); //get name of the product
  echo "<br/>";
  echo (float) $product->getPrice(); //get price as cast to float
   echo "<br/>";
  echo $product->getDescription(); //get description
   echo "<br/>";

   echo $product->getSku(); //get sku
   echo "<br/>";
echo (int)Mage::getModel('cataloginventory/stock_item')
                ->loadByProduct($product)->getQty(); //get the qty of the product
   echo "<br/>";


  // getCategoryIds(); returns an array of category IDs associated with the product
  foreach ($product->getCategoryIds() as $category_id) {
      $category = Mage::getModel('catalog/category')->load($category_id);
       echo "<br/>";
 echo $category->getName(); //get name of the category && sub-category
       echo "<br/>";
  }
  echo '<br/>';

  //gets the image url of the product


             //var_dump($product->getMediaGalleryImages());
echo "<br/>";
  echo $product->getProductUrl();  //gets the product url
  echo '<br />';
echo $product->getSize();  
  echo '<br />';
$product1 = Mage::getModel('catalog/product')->load($product->getID())->getMediaGalleryImages();//product

$items = array();

foreach($product1 as $gimage) {
    $items[] = $gimage['url'];
}
$t = implode(',', $items);

echo $t;

echo "</br>";
}

Now, how will i be able to fetch the quantity and size in the format mentioned above foreach product using the above collection ??

Best Answer

The following snippet is an example to retrieve what you need.

$products = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToSelect('sku')
    ->addAttributeToSelect('name')
    ->addAttributeToSelect('type_id');

if (Mage::helper('catalog')->isModuleEnabled('Mage_CatalogInventory')) {
    $products->joinField('qty',
        'cataloginventory/stock_item',
        'qty',
        'product_id=entity_id',
        '{{table}}.stock_id=1',
        'left');
}

foreach ($products as $product) {
    printf(
        "Type: %s - SKU: %s - Name: %s - Qty: %d" . PHP_EOL,
        $product->getTypeId(),
        $product->getSku(),
        $product->getName(),
        $product->getQty()
    );
}

Refer to Mage_Adminhtml_Block_Catalog_Product_Grid to see some examples about how to properly retrieve product collections.

Hope it helps.

EDIT

This one should give the desired output:

/** @var Mage_Catalog_Model_Product $confProduct */
// Replace this with your configurable product instance
$confProduct = Mage::getModel('catalog/product')->load(877); // sample ID

$productIds = $confProduct
    ->getTypeInstance(true)
    ->getUsedProductIds($confProduct);

$confAttributeCodes = array_map(
    function($attribute) {
        return $attribute['attribute_code'];
    },
    $confProduct->getTypeInstance(true)->getConfigurableAttributesAsArray($confProduct)
);

$products = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToSelect('sku')
    ->addAttributeToSelect('name')
    ->addAttributeToSelect('type_id')
    ->addAttributeToSelect($confAttributeCodes)
    ->addFieldToFilter('entity_id', array('in' => $productIds));

if (Mage::helper('catalog')->isModuleEnabled('Mage_CatalogInventory')) {
    $products->joinField('qty',
        'cataloginventory/stock_item',
        'qty',
        'product_id=entity_id',
        '{{table}}.stock_id=1',
        'left');
}

$result = array();
foreach ($products as $product) {
    $label = array_reduce(
        $confAttributeCodes,
        function ($carry, $item) use ($product) {
            return $carry . $product->getAttributeText($item) . ' ';
        },
        ''
    );
    $result[trim($label)] = $product->getQty();
}
echo json_encode($result);

To get the results for each configurable product, remove the line that begins with $confProduct = ... and wrap all the code block within the following foreach

$confProducts = Mage::getModel('catalog/product')->getCollection()
    ->addFieldToFilter('type_id', Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE);
foreach ($confProducts as $confProduct) { 
    // put the above code here, without $confProduct assignment
}

Note: I suggest you to add necessary filters to the configurable products collection (visibility, status etc.)

Related Topic