我在帳戶表的玩具列中有以下 JSON 值
{
"truck":{
"qty":10,
"price":53
},
"doll":{
"qty":15,
"price":15
}
}
現在我想為此添加新值{"animals":{"qty":1,"price":4},"stickers":{"qty":12,"price":12}}。我試過下面的方法
$new_toys = [
'animals' => ['qty' => 1, 'price' => 4],
'stickers' => ['qty' => 12, 'price' => 12]
];
$old_tyoys = $account->toys;
array_push($old_tyoys, $new_toys);
$account->toys = $old_tyoys;
$account->save();
但這將更新列如下
{
"truck":{
"qty":10,
"price":53
},
"doll":{
"qty":15,
"price":15
},
"0":{
"animals":{
"qty":1,
"price":4
},
"stickers":{
"qty":12,
"price":12
}
}
}
但我想要它如下
{
"truck":{
"qty":10,
"price":53
},
"doll":{
"qty":15,
"price":15
},
"animals":{
"qty":1,
"price":4
},
"stickers":{
"qty":12,
"price":12
}
}
我需要在代碼中更改什么?謝謝
uj5u.com熱心網友回復:
替換array_push($old_tyoys, $new_toys);為collect($account->toys)->merge($new_toys)->all();
所以你的方法代碼會變成
$new_toys = [
'animals' => ['qty' => 1, 'price' => 4],
'stickers' => ['qty' => 12, 'price' => 12]
];
$merged = collect((array)$account->toys)->merge(new_toys)->all();
//Or
$merged = array_merge((array) $account->toys, $new_toys);
$account->toys = $merged;
$account->save();
uj5u.com熱心網友回復:
那是因為您array_push用于聚合這兩個物件,并且在內部它將您的第二個引數添加為分配給數字 index 的值0。嘗試使用array_merge.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/485546.html
