我有一個包含食物項目的數據數組,並且看起來像這樣。Laravel:循環訪問一個數組並將其轉換爲帶有原始數組的內部密鑰
[
{
"itemId": 80001,
"name": "FRENCH FRIES SMALL",
"description": "More delicious than ever, our signature piping hot, thick cut Salted French Fries are golden on the outside and fluffy on the inside.",
"price": 6,
"slug": "french-fries-small-80001"
},
{
"itemId": 80002,
"name": "FRENCH FRIES MEDIUM",
"description": "More delicious than ever, our signature piping hot, thick cut Salted French Fries are golden on the outside and fluffy on the inside.",
"price": 7,
"slug": "french-fries-medium-80002"
},
{
"itemId": 80003,
"name": "FRENCH FRIES LARGE",
"description": "More delicious than ever, our signature piping hot, thick cut Salted French Fries are golden on the outside and fluffy on the inside.",
"price": 8,
"slug": "french-fries-large-80003"
},
{
"itemId": 80052,
"name": "CRINCKLE WEDGES SMALL",
"description": "CRINCKLE WEDGES SMALL",
"price": 7,
"slug": "crinckle-wedges-small-80052",
"sequence": 14
},
{
"itemId": 80053,
"name": "CRINCKLE WEDGES MEDIUM",
"description": "CRINCKLE WEDGES MEDIUM",
"price": 8,
"slug": "crinckle-wedges-medium-80053",
"sequence": 15
},
{
"itemId": 80054,
"name": "CRINCKLE WEDGES LARGE",
"description": "CRINCKLE WEDGES LARGE",
"price": 9,
"slug": "crinckle-wedges-large-80054",
"sequence": 16
},
]
現在我通過陣列必須循環,如果名下有兩種小型,中型或大型我必須重新格式化數據,因此它應該是這個樣子例如
{
"itemId": 80001,
"name": "FRENCH FRIES",
"description": "More delicious than ever, our signature piping hot, thick cut Salted French Fries are golden on the outside and fluffy on the inside.",
"itemModifiers":[
{
"itemId": 80001,
"name": "FRENCH FRIES SMALL",
"description": "More delicious than ever, our signature piping hot, thick cut Salted French Fries are golden on the outside and fluffy on the inside.",
"price": 6,
"slug": "french-fries-small-80001"
},
{
"itemId": 80002,
"name": "FRENCH FRIES MEDIUM",
"description": "More delicious than ever, our signature piping hot, thick cut Salted French Fries are golden on the outside and fluffy on the inside.",
"price": 7,
"slug": "french-fries-medium-80002"
},
{
"itemId": 80003,
"name": "FRENCH FRIES LARGE",
"description": "More delicious than ever, our signature piping hot, thick cut Salted French Fries are golden on the outside and fluffy on the inside.",
"price": 8,
"slug": "french-fries-large-80003"
}
],
"slug": "french-fries-80001",
"sequence": 8
}
客戶的遺留系統設計不當,他們被要求適當的數據格式爲更顆粒化格式的API。我試圖弄清楚如何做到這一點。請注意,原始數組比我的例子有更多的項目,我應該循環每一個。我應該從頭重建數據嗎?或者有更好的方式來循環訪問數組?
取而代之的是對數據進行額外處理,並且每次使用循環對大量數據進行重新格式化,如果根據您的方便重新構建原始數組,那聽起來會更好。 –
您使用的是什麼版本的Laravel? –
@RossWilson Laravel 5.1 –