我有一个示例表,如下所示:
| id | is_new | cate |
| 0 | 1 | [5] |
| 1 | 1 | [5] |
| 2 | 1 | [7] |
| 3 | 1 | [6] |
在我调用以下函数之后
$product = Products::where('is_new', 1)->get();
该集合具有以下数据结构
Collection {#1284 ▼
#items: array:4 [▼
0 => Products {#1285 ▶}
1 => Products {#1286 ▶}
2 => Products {#1287 ▶}
3 => Products {#1288 ▶}
]
}
我还可以通过以下方式返回类别 ID 列表:
$category = Category::where('type', 2)->pluck('id')->all();
我想知道有没有什么好的方法来实现基于 cate 的以下结构(或类似结构)。我可以使用蛮力方法通过循环 $category 然后手动添加到新集合来创建它,我认为有更好的方法来做到这一点。
Collection {#1284 ▼
#items: array:3 [▼
5 => array:2 [▼
0 => Products {#1285 ▶}
1 => Products {#1286 ▶}
]
6 => Products {#1287 ▶} or 6 => array:1 [ 0 => Products {#1287 ▶} ]
7 => Products {#1288 ▶}
]
}
基于答案的解决方案更新:
$product->groupBy(function($item) {
return $item['cate'][0]; //because the entry is a list
});
幕布斯7119047