Answer the question
In order to leave comments, you need to log in
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');
<?php foreach ($categories as $one) {
echo '<h2>', $one->name; echo '</h2>';
foreach ($one->? as $prod) {
$prod->name;
}
}?>
Answer the question
In order to leave comments, you need to log in
Don't reinvent the wheel. Your code can and should be simply implemented using relation and eager loading
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 questionAsk a Question
731 491 924 answers to any question