猿问

如何在 Laravel 中使用数组推送

我正在尝试使用数组推送在 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

           }

         }

        ]



九州编程
浏览 161回答 2
2回答

繁星coding

您正在实际要推送的数组之外使用数组推送。您的data_chart数组有一个名为的嵌套数组,data因此您可以做的是围绕数组循环,例如:foreach($data['data_chart'] as $row){    $row->color = "#9c1d1d";  // you are inside the nested data array}当您构建了$data数组并希望在其中添加额外的项目(颜色)时,您可以使用上述循环。

动漫人物

Laravel 为我们提供了数组辅助函数,通过它我们可以无循环地做这些事情。data_set($data_chart, 'data.*.color', $color);欲了解更多与数组相关的辅助函数,请单击此处
随时随地看视频慕课网APP
我要回答