0

i got this little problem with an array. I have products that belong to one or more categories and i need to display them as an array. First, this is my code to get categories from product 1 only:

    $prod = $this->getDi()->productTable->load(1);
    $prod_cat = $prod->getCategories();
    print_r($prod_cat);

This will output this:

Array ( [0] => 1 ) 

So far so good. However, i need to do the same for all the products in existence at once. So im doing this:

$act_prod = Array ( 0 => 1 ); //array can contain more than one product, as of now it only contains one

foreach ($act_prod as $act) {
         $cat = $this->getDi()->productTable->load($act);
         $active_cat[$act] = $cat->getCategories(); 
        } 
print_r($active_cat);

But this will output:

Array ( [1] => Array ( [0] => 1 ) ) 

which is not what i need but this instead:

Array ( [0] => 1 ) 

I cant figure out whats wrong. Could you please give me a hint?

Thank you.

4
  • 1
    I'm quite confused. What is your expected output in the loop? Commented Apr 14, 2014 at 2:46
  • I expect this: Array ( [0] => 1 ) Commented Apr 14, 2014 at 2:53
  • what are you getting from $cat->getCategories(); Commented Apr 14, 2014 at 2:55
  • I get this: Array ( [1] => Array ( [0] => 1 ) ) which is not what i expect Commented Apr 14, 2014 at 3:00

1 Answer 1

1

$cat->getCategories() returns an array, you add an array to another array each iteration, so is the result.

If you want to merge all the categories to a array, use array_merge instead:

$active_cat = array();
foreach ($act_prod as $act) {
    $cat = $this->getDi()->productTable->load($act);
    $active_cat = array_merge($active_cat, $cat->getCategories()); 
} 

And side note, it's quite not efficient do such loop, you may get all the categories with just one query.

Sign up to request clarification or add additional context in comments.

1 Comment

Are you sure about that one? Why is $active_cat being defined as something that contains $active_cat as well?

Your Answer

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.