6

I am using the Function $collection->removeItemByKey($key);

As i know that the above function remove product one by one based on the key and that key is product id,

My Question is Can we remove the product using other attribute instead of product id.

I have custom attribute called product_creator_id, Can I use this custom Attribute to remove the product from collection as removeItemByKey works.

foreach ($collection->getItems() as $key => $_product) {
       //product
       //$collection->removeItemByKey($key);
       echo $key;
       print_r($_product->getName());
}
8

Yes it is possible, but not as efficient as removing it by ID. The removeItemByKey method uses an unset on the array, so has constant time. To remove a custom item by your attribute, you will need to do a loop:

foreach ($collection as $product) {
   if ($product->getProductCreatorId() == 'YOUR_VALUE') {
       $collection->removeItemByKey($product->getId());
   }
}

Another option is to filter it out already when you query the database:

$valuesYouDoNotWant = array(1,2,3);
$collection->addAttributeToFilter('product_creator_id', array('nin' => $valuesYouDoNotWant));

where nin stands for not in array

3

I got the solution.

foreach ($collection as $key => $product) {
      if ($productStoreId != $currentStoreId) {
           $collection->removeItemByKey($key);
      }
}
  • This is pretty much what my answer is. Why don't you just filter for the store ID in the collection right away? – mpaepper Jun 4 '14 at 16:07
1
$items = $collection->getItemsByColumnValue('columnname', 'value')
foreach ($items as $item) {
    $collecton->removeItemByKey($item->getId());
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.