Laravel 4 - 迭代数组并将值输入刀片

时间:2014-11-27 16:07:31

标签: php arrays laravel

我正在使用etrepat/baum,我正在使用以下命令检索根类别的所有子项:

$children = $category->children()->get();

然后,为了检索存储在子类别下的所有产品,我正在进行foreach循环以获取子类别的id和另一个foreach将产品存储在$children_products[]数组中,如所以:

// store the ids of the children categories
foreach ($children as $child) {
     $children_ids[] = $child->id;
}

// store the products that children categories have
foreach($children_ids as $val) {
     $children_products[] = Product::where('category_id', '=', $val)->get();
}

然后我将$children_products数组发送到视图以呈现结果。虽然,这是为每个具有产品或为空的子类别呈现为不同的数组。

[] [{"id":1,"category_id":21,"brand_id":1,"title":"test","description":"Etiam aliquam sem ac velit feugiat elementum. Nunc eu elit velit, nec vestibulum nibh. Curabitur ultrices, diam non ullamcorper blandit, nunc lacus ornare nisi, egestas rutrum magna est id nunc. Pellentesque imperdiet malesuada quam, et rhoncus eros auctor eu. Nullam vehicula metus ac lacus rutrum nec fermentum urna congue. Vestibulum et risus at mi ultricies sagittis quis nec ligula. Suspendisse dignissim dignissim luctus.","price":"1000.00","availability":1,"image":"img\/products\/2014-11-24-14:29:33-00064736.jpg","created_at":"2014-11-24 14:29:34","updated_at":"2014-11-24 14:29:34"}] [] [] [] [] []

有没有办法迭代这些数组并将产品存储在数组中?

1 个答案:

答案 0 :(得分:0)

您可以简化产品查询:

$children_products = Product::whereIn('category_id', $children->lists('id'))->get();

然后可能只是迭代Blade中的值?

@foreach ($children_products as $product)
{{ $product->title }}
@endforeach