为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 Laravel 中使用数组推送

如何在 Laravel 中使用数组推送

PHP
九州编程 2021-08-27 09:15:00
我正在尝试使用数组推送在 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数组并希望在其中添加额外的项目(颜色)时,您可以使用上述循环。


查看完整回答
反对 回复 2021-08-27
?
动漫人物

TA贡献1815条经验 获得超10个赞

Laravel 为我们提供了数组辅助函数,通过它我们可以无循环地做这些事情。

data_set($data_chart, 'data.*.color', $color);

欲了解更多与数组相关的辅助函数,请单击此处


查看完整回答
反对 回复 2021-08-27
  • 2 回答
  • 0 关注
  • 160 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信