我正在嘗試使用數組推送在 Laravel 數組中添加新項目,但遇到了一些麻煩。我想在“data_chart”中添加名為“Color”的新項目。我已經嘗試過使用數組 Push 和數組 Unshift。有沒有更好的方法來做到這一點?我想要這樣的結果:"data": [ { "id": 29, "title": "get data users", "function_name": "selectDataUser", "function_drop": "selectDataUser", "type_of_chart": "Pie", "embed": null, "created_at": "2019-06-15 03:26:09.000", "updated_at": null, "data_chart": { "data": [ { "name": "Administrator", "total": "100", "color" "#9c1d1d" //I want color should be here in this line }, { "name": "Staff", "total": "100", "color" "#9c1d1d" //new item named Color }, ], } } ]但是當我嘗試使用數組推送時,結果變成了這樣:"data": [ { "id": 29, "title": "get data users", "function_name": "selectDataUser", "function_drop": "selectDataUser", "type_of_chart": "Pie", "embed": null, "created_at": "2019-06-15 03:26:09.000", "updated_at": null, "data_chart": { "data": [ { "name": "Administrator", "total": "100" //color should be in here }, { "name": "Staff", "total": "100" //color should be in here } ], "color": "#9c1d1d" //idk but the color shouldn't like this } } ]
2 回答

繁星coding
TA貢獻1797條經驗 獲得超4個贊
您正在實際要推送的數組之外使用數組推送。
您的data_chart數組有一個名為的嵌套數組,data因此您可以做的是圍繞數組循環,例如:
foreach($data['data_chart'] as $row){
$row->color = "#9c1d1d"; // you are inside the nested data array
}
當您構建了$data數組并希望在其中添加額外的項目(顏色)時,您可以使用上述循環。
- 2 回答
- 0 關注
- 188 瀏覽
添加回答
舉報
0/150
提交
取消