S
S
sdgs4s4 .2018-04-24 15:55:28
Yii
sdgs4s4 ., 2018-04-24 15:55:28

Yii2 -> Outputting two arrays foreach?

I'm trying to display categories and products immediately to them.
There is a controller:

$categories = Category::find()->where(['parent_id' => $id, 'status' => '1'])->indexBy('id')->all();
        
        $categoryIds = array_keys($categories);

        $categoryIds[] = $id;
        
        $products = Product::find()->where(['category_id' => $categoryIds, 'status' => '1'])->addOrderBy('id DESC');

There is a view
<?php foreach ($categories as $one) {
            echo '<h2>', $one->name; echo '</h2>';
            foreach ($one->? as $prod) {
                $prod->name;
            }
        }?>

How to write so that each category displays its own products
5adf293d4c562411024715.jpeg

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Fedorov, 2018-04-24
@Encoderast

Don't reinvent the wheel. Your code can and should be simply implemented using relation and eager loading

M
Maxim Timofeev, 2018-04-24
@webinar

You show the contents of the arrays, it is not clear what is in them, how are they connected? But I can throw an abstract idea:

foreach($product as $p){
   echo $category[$p->cat_id]['name'];
   echo $p->name;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question