Laravel Collect集合用pluck取多维数组中某个字段值
例如目前有多维数组结构如下:
[
{
"id": 29,
"shop_id": 15,
"good_id": 2520,
"type": "FIX",
"name": "1312",
"freedom_count": 1,
"group_items": [
{
"id": 2461,
"good_group_id": 29,
"shop_id": 15,
"good_id": 1687,
"quantity": 1,
"add_price": 3000,
"sort": 1,
"good": {
"id": 1687,
"title": "可乐",
"price": 12000,
"unit": "杯",
"status": "NORMAL"
}
},
{
"id": 2459,
"good_group_id": 29,
"shop_id": 15,
"good_id": 2516,
"quantity": 1,
"add_price": 1000,
"sort": 1,
"good": {
"id": 2516,
"title": "雪碧",
"price": 10000,
"unit": "杯",
"status": "NORMAL"
}
},
{
"id": 62,
"good_group_id": 29,
"shop_id": 15,
"good_id": 2460,
"quantity": 2,
"add_price": 0,
"sort": 1,
"good": {
"id": 2460,
"title": "咖啡",
"price": 9000,
"unit": "杯",
"status": "NORMAL"
}
}
]
},
{
"id": 36,
"shop_id": 15,
"good_id": 2520,
"type": "FREEDOM",
"name": "自由搭配",
"freedom_count": 2,
"group_items": [
{
"id": 2464,
"good_group_id": 36,
"shop_id": 15,
"good_id": 2460,
"quantity": 1,
"add_price": 0,
"sort": 1,
"good": {
"id": 2460,
"title": "圣代奶茶",
"price": 9000,
"unit": "杯",
"status": "NORMAL"
}
},
{
"id": 2465,
"good_group_id": 36,
"shop_id": 15,
"good_id": 1687,
"quantity": 1,
"add_price": 0,
"sort": 1,
"good": {
"id": 1687,
"title": "珍珠奶茶",
"price": 12000,
"unit": "杯",
"status": "NORMAL"
}
}
]
}
]
要从以上3维数组中取出最底层good 对象的title 属性,用以下方式可以直接获取:
$json = '
[
{
"id": 29,
"shop_id": 15,
"good_id": 2520,
"type": "FIX",
"name": "1312",
"freedom_count": 1,
"group_items": [
{
"id": 2461,
"good_group_id": 29,
"shop_id": 15,
"good_id": 1687,
"quantity": 1,
"add_price": 3000,
"sort": 1,
"good": {
"id": 1687,
"title": "可乐",
"price": 12000,
"unit": "杯",
"status": "NORMAL"
}
},
{
"id": 2459,
"good_group_id": 29,
"shop_id": 15,
"good_id": 2516,
"quantity": 1,
"add_price": 1000,
"sort": 1,
"good": {
"id": 2516,
"title": "雪碧",
"price": 10000,
"unit": "杯",
"status": "NORMAL"
}
},
{
"id": 62,
"good_group_id": 29,
"shop_id": 15,
"good_id": 2460,
"quantity": 2,
"add_price": 0,
"sort": 1,
"good": {
"id": 2460,
"title": "咖啡",
"price": 9000,
"unit": "杯",
"status": "NORMAL"
}
}
]
},
{
"id": 36,
"shop_id": 15,
"good_id": 2520,
"type": "FREEDOM",
"name": "自由搭配",
"freedom_count": 2,
"group_items": [
{
"id": 2464,
"good_group_id": 36,
"shop_id": 15,
"good_id": 2460,
"quantity": 1,
"add_price": 0,
"sort": 1,
"good": {
"id": 2460,
"title": "圣代奶茶",
"price": 9000,
"unit": "杯",
"status": "NORMAL"
}
},
{
"id": 2465,
"good_group_id": 36,
"shop_id": 15,
"good_id": 1687,
"quantity": 1,
"add_price": 0,
"sort": 1,
"good": {
"id": 1687,
"title": "珍珠奶茶",
"price": 12000,
"unit": "杯",
"status": "NORMAL"
}
}
]
}
]
';
$arr = json_decode($json, true);
$titles = collect($arr)->pluck('group_items.*.good.title')->collapse()->toArray();
dd($titles);
每多一层级的数组可以用通配符 * 代表,之后继续找下级对象字段即可;collapse函数是将多个数组合并为单个数组;
结果:
array:5 [▼
0 => "可乐"
1 => "雪碧"
2 => "咖啡"
3 => "圣代奶茶"
4 => "珍珠奶茶"
]
|