Reputation: 3089
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.
Upvotes: 0
Views: 47
Reputation: 160853
$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.
Upvotes: 1