Magento 1.9 – How to Get All Values of a Custom Attribute

collection;magento-1.9product-attributeproduct-collection

I have a custom product attribute test_id which is a text field. I want to get all the values assigned to this attribute within a given product collection.

I found the following way of doing it. But I need to know if there is a better solution.

public function getAllTestIds() {
    $allValues = array();
    $collection = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('*');
    foreach($collection as $product) {
        $data = $product->getData();
        if(trim($data['test_id']) != '') {
            $allValues[] = $data['test_id'];
       }
   }
return $allValues;
}

Best Answer

@Sukeshini,add groupByAttribute() to get data of unique data and remove null .

public function getAllTestIds() {
    $allValues = array();
    $collection = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('*')->addAttributeToFilter('test_id', array(
    'notnull' => true,
    ))->groupByAttribute('test_id');

    foreach($collection as $product) {
        $data = $product->getData();
            $allValues[] = $data['test_id'];
       }
   }
return $allValues;
}
Related Topic