Array_merge в laravel

У меня есть данные, которые я возвращаю в коллекцию, но они не возвращаются, как я хочу, и мне нужна помощь, чтобы это исправить.

array:11 [▼
0 => Collection {#2762 ▼
#items: array:3 [▼
0 => Product {#2758 ▶}
1 => Product {#2759 ▶}
2 => Product {#2760 ▶}
]
}
1 => Collection {#2792 ▼
#items: []
}
2 => Collection {#2948 ▼
#items: []
}
3 => Collection {#3102 ▼
#items: []
}
4 => Collection {#3216 ▼
#items: []
}
5 => Collection {#2886 ▼
#items: array:10 [▶]
}
6 => Collection {#2920 ▼
#items: array:3 [▶]
}
7 => Collection {#3046 ▼
#items: array:12 [▶]
}
8 => Collection {#3074 ▼
#items: []
}
9 => Collection {#3188 ▼
#items: array:7 [▶]
}
10 => Collection {#3288 ▼
#items: []
}
]
$category = Category::where('slug','=',$catslug)->with('childs', 'parent')->first();


$pp1[] = Product::where('category_id',$category->id)->get();

foreach($category->childs as $first){
$pp2[] = Product::where('category_id',$first->id)->get();
if(count($first->childs)> 0){
foreach($first->childs as $second){
$pp3[] = Product::where('category_id',$second->id)->get();
}
}
}

$products = array_merge($pp1,$pp2,$pp3);

dd($products);

Он должен возвращать все продукты из всех массивов только в одном массиве и не классифицироваться по Collection {#2792 ▼ Мне нужно получить только коллекции с элементами, а не те, которые пусты.

Любая идея?

Я также попробовал это:

$pp1 = [];
$pp2 = [];
$pp3 = [];
$pp1 = Product::where('category_id',$category->id)->get();

foreach($category->childs as $first){
$pp2 = Product::where('category_id',$first->id)->get();
if(count($first->childs)> 0){
foreach($first->childs as $second){
$pp3 = Product::where('category_id',$second->id)->get();
}
}
}

это возвращает:

array_merge(): Argument #1 is not an array

-1

Решение

Вы можете получить все товары этой категории, его детей и его внуков, как,

$category = Category::where('slug','=',$catslug)
->with([
'products',
'childs.products',
'childs.childs.products',
'parent'
])
->first()
->toArray();

$products = array_merge([
data_get($category, 'products'),
array_collapse(data_get($category, 'childs.*.products')),
array_collapse(data_get($category, 'childs.*.childs.*.products'))
]);

Скрипка: https://implode.io/ebXrD8

0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector