我正在嘗試使用數(shù)組推送在 Laravel 數(shù)組中添加新項(xiàng)目,但遇到了一些麻煩。我想在“data_chart”中添加名為“Color”的新項(xiàng)目。我已經(jīng)嘗試過使用數(shù)組 Push 和數(shù)組 Unshift。有沒有更好的方法來做到這一點(diǎn)?我想要這樣的結(jié)果:"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 }, ], } } ]但是當(dāng)我嘗試使用數(shù)組推送時(shí),結(jié)果變成了這樣:"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貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超4個(gè)贊
您正在實(shí)際要推送的數(shù)組之外使用數(shù)組推送。
您的data_chart數(shù)組有一個(gè)名為的嵌套數(shù)組,data因此您可以做的是圍繞數(shù)組循環(huán),例如:
foreach($data['data_chart'] as $row){
$row->color = "#9c1d1d"; // you are inside the nested data array
}
當(dāng)您構(gòu)建了$data數(shù)組并希望在其中添加額外的項(xiàng)目(顏色)時(shí),您可以使用上述循環(huán)。

動(dòng)漫人物
TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超10個(gè)贊
Laravel 為我們提供了數(shù)組輔助函數(shù),通過它我們可以無循環(huán)地做這些事情。
data_set($data_chart, 'data.*.color', $color);
欲了解更多與數(shù)組相關(guān)的輔助函數(shù),請(qǐng)單擊此處
- 2 回答
- 0 關(guān)注
- 185 瀏覽
添加回答
舉報(bào)
0/150
提交
取消