0
我有一個Laravel集合,如下所示,它是作爲數據庫查詢(查詢生成器,而不是Eloquent)的結果而獲得的。格式Laravel集合
Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[0] => stdClass Object
(
[product_name] => Product 1
[sub_product_name] => sub_prod_1
)
[1] => stdClass Object
(
[product_name] => Product 1
[sub_product_name] => sub_prod_2
)
[2] => stdClass Object
(
[product_name] => Product 1
[sub_product_name] => sub_prod_3
)
[3] => stdClass Object
(
[product_name] => Product 2
[sub_product_name] => sub_prod_21
)
[4] => stdClass Object
(
[product_name] => Product 2
[sub_product_name] => sub_prod_22
)
[5] => stdClass Object
(
[product_name] => Product 2
[sub_product_name] => sub_prod_23
)
[6] => stdClass Object
(
[product_name] => Product 3
[sub_product_name] => sub_prod_31
)
)
)
現在我想轉換數組,如下所示,並將其作爲API響應發送。基本上這是初始化每個產品的計數,然後計數將被添加到這個。
Array
(
[Product 1 ] => stdClass Object
(
sub_prod_1 => 0,
sub_prod_2 => 0,
sub_prod_3 => 0
),
[Product 2 ] => stdClass Object
(
sub_prod_21 => 0,
sub_prod_22 => 0,
sub_prod_23 => 0
),
[Product 3 ] => stdClass Object
(
sub_prod_31 => 0,
)
)
它也是好的,如果它有一個更層,我的意思是像[0] [產品1]
我已經使用GROUPBY這樣
$productPoints = $productCollection->groupBy(function ($item) {
return $item->product_name;
});
但不給予預期的結果。我如何使用Laravel收集方法來做到這一點?