1

I'm creating a list of products, which is filtered to only show products within certain categories in Magento. I'm using the AddAttributeToFilter which is working fine:

$products->addAttributeToFilter('category_id', array('in' => array(105,106)));

This seems to work fine and it retrieves products that are in category 105 and 106.

However, I'm building a form that will dynamically pass the IDs into the filter depending on a user's selection. So in some case there will only be 2 category IDs, other times there maybe 6 different category IDs.

For example:

$products->addAttributeToFilter('category_id', array('in' => array(105,106,124,158,147)));

However, I can't figure out how I can create the array dynamically.

I tried this but it doesn't work:

$val = "105,106,124,158,147";
$products->addAttributeToFilter('category_id', array('in' => array('$val')));

Any help would be much appreciated.

asked Feb 3, 2015 at 13:12

1 Answer 1

1

What you tried isn't an array, but a string.

Try this instead:

$val = "105,106,124,158,147";
$val_array = explode(",", $val);
$products->addAttributeToFilter('category_id', array('in' => array($val_array)));

The explode command will split the string by the comma and produce an array for it.

answered Feb 3, 2015 at 13:16
2
  • Wow, thanks that was super fast! Tried it out and it works perfectly. Thanks again. Commented Feb 3, 2015 at 13:36
  • No problem, glad to help :) Commented Feb 3, 2015 at 13:37

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.