Magento – how to get attribute values (select type) from a product collection

attributesdropdown-attributemagento-1

I need to retrieve all values of an attribute (multi-option select type) from a filtered collection of products.

First i want to get a collection of products, then filter this collection based on certain category and certain attribute.For remaining products in the collection, I want to retrieve the values (unique) of my multi-option select attribute.

So far I have some code that doesn't work

$attributeCode = 'compatible_printers';
$ctname=$_GET['ctn'];

$collection = Mage::getModel('catalog/product')->getCollection();

$collection->addAttributeToSelect('name'); 
$collection->addAttributeToSelect('manufacturer');
$collection->addAttributeToSelect('ink_type');
$collection->addAttributeToSelect($attributeCode); // this is the required attribute

$collection->addFieldToFilter(array(
array('attribute'=>'manufacturer','eq'=>$ctname), 
 )); 


$collection->addFieldToFilter(array(
array('attribute'=>'ink_type','eq'=>'Laserjet Toner'), 
 )); 
$collection->addAttributeToFilter($attributeCode, array('notnull' => true));
    $collection->addAttributeToFilter($attributeCode, array('neq' => ''));

// i m trying to get the attribute values in the following array
$usedAttributeValues = array_unique($collection->getColumnValues($attributeCode));

I have looked for similar questions and found some anwsers but they don't work for me. Can someone advice how to make the above code work?

Best Answer

You'll need to get a collection of the desired products and iterate through it to get the attribute values. Like this..

$attributeCode = 'compatible_printers';
$ctname = $_GET['ctn'];
$usedAttributeValues = array();

$collection = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToSelect(array('name', 'manufacturer', 'ink_type', $attributeCode))
    ->addAttributeToFilter('manufacturer', $ctname)
    ->addAttributeToFilter('ink_type', 'Laserjet Toner')
    ->addAttributeToFilter($attributeCode, array('notnull' => true))
    ->addAttributeToFilter($attributeCode, array('neq' => ''));

foreach ($collection as $product) {
    $usedAttributeValues[] = $product->getData($attributeCode);
}

$usedAttributeValues = array_unique($usedAttributeValues);