1

i have products that belong to categories and i need to get such categories and output them as a single array. This is my this code:

    $act_prod = array(0=>1,1=>10);
    $active_cat = array();

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

    print_r($active_cat);

Which will output:

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

This means product 1 belongs to category 1 and product 10 to category 2 but i dont need all that. I only need the categories like this: Array (1, 2) or Array (0=>1, 1=>2).

What should i use so i get the correct output?

Thank you.

5
  • Is product relates with the single category always ? Commented Apr 14, 2014 at 5:05
  • Products can have more than one category. Commented Apr 14, 2014 at 5:07
  • Your $cat->getCategories(); is returning an array. Hence, each key in your $active_cat contains an array Commented Apr 14, 2014 at 5:08
  • @CainNuke - In that case how should your expected array will look ? Commented Apr 14, 2014 at 5:08
  • It can either look like this: Array ( [0] => 1 [1] => 2 ) or like this: Array (1, 2) Commented Apr 14, 2014 at 5:12

3 Answers 3

1

Modified your code to build up just the list you want.

$act_prod = array(0=>1,1=>10);
$active_cat = array(); // will be a flat list of categories

foreach ($act_prod as $act) {
    $cat = $this->getDi()->productTable->load($act);
    foreach($cat->getCategories as $category) {
        // if we have not seen this category on any previous category, push it
        if(!in_array($cat->getCategories(), $active_cat)) {
            array_push($active_cat, $cat->getCategories()); 
        }
    }
} 

// if desired, sort array first
print_r($active_cat);
Sign up to request clarification or add additional context in comments.

Comments

1
foreach ($act_prod as $act) {
    $cat = $this->getDi()->productTable->load($act);
    $cats = $cat->getCategories(); 

    foreach($cats as $cat)
    {
         $active_cat[] = $cat['cat_id'];
    }
} 

Assuming cat_id is your category id

1 Comment

this solution will leave duplicates in the returned array.
1

You need to flatten the $active_cat array, like this:

// ...
foreach ($cat->getCategories() as $category) {
    $active_cat[] = $category;
}
// ...

Afterwards, make sure there are no duplicates:

$active_cat = array_unique($active_cat);

Comments

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.