我正在尝试使用数组推送在 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 关注
- 160 浏览
添加回答
举报
0/150
提交
取消