亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 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 關注
  • 188 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號