Magento 1.8 – How to Get Custom Data in Item Collection Array

collection;magento-1.8model

This is somewhat confusing.. I hope my explanation is clear.

As we all know magento converts a php object(I don't know what it is exactly) to an Array by using:

$item->getData();    // Where $item is an item from a product collection

The above code does covert the object to an Array, but I want to add my own custom fields to it.

So, I tried the following while preparing the collection

foreach($collection as $item){
    $item->setData('custom_field', $value);  // Also tried $item->setCustomField($value);
}

By doing the above, I can get the custom_field value by doing $item->getCustomField() or $item->getData('custom_field'); but I can't see this custom_field key in array when I am doing

$item->getData();

For Example:

Let us say, If I do

echo $item->getData();

I can see the following array in dump:

array(4) {
  ["entity_id"] => string(3) "623"
  ["type_id"] => string(12) "configurable"
  ["created_at"] => string(19) "2012-07-30 22:14:09"
  ["updated_at"] => string(19) "2014-01-04 02:02:08"
}

But I want to see the following Array:

array(5) {
  ["entity_id"] => string(3) "623"
  ["type_id"] => string(12) "configurable"
  ["created_at"] => string(19) "2012-07-30 22:14:09"
  ["updated_at"] => string(19) "2014-01-04 02:02:08"
  ["custom_field"] => string(5) "Hello"
}

Best Answer

I think you just need to save your item , then you can use it :

       foreach($collection as $item){
            $item->setData('custom_field', $value);  // or $item->setCustomField($value);
            $item->save();
        }
var_dump($collection->getFirstItem()->getData()); // print first item