JSON数据库更新丢失键值



我在我的DB中得到了这个(23是我的图片ID(:

{"23" : {"13x18":"5","20X30":"5","30x45":"4","digital":"4"}}

我想在同一个位置添加另一个数据,就像这个一样,所以它看起来像这样:

["23" : {"13x18":"5","20X30":"5","30x45":"4","digital":"4"}, 
"42" : {"13x18":"2","20X30":"1","30x45":"3","digital":"1"}]

以下是使用的代码:

$clientChoice = [];
$clientChoice[$post['picId']] = $test;
$select = (new GalleryCategoriesModel)->findByUrl($post['url']);
if($select['clientChoice'] != null){
$tabs = json_decode($select['clientChoice'], true);
$new = array_merge($tabs, $clientChoice);
$chosen = json_encode($new);
} else {
$chosen = json_encode($clientChoice);
}
$update = (new GalleryCategoriesModel)->update(['clientChoice'=>$chosen], $post['id']);

这是我得到的结果:

[{"13x18":"5","20X30":"5","30x45":"4","digital":"4"},
{"13x18":"2","20X30":"1","30x45":"3","digital":"1"}]

我错过了什么或做错了什么?

-----------------更正------------------

感谢给出的答案,以下是我现在所做的:

$clientChoice = [];
$clientChoice[$post['picId']] = $test;
$select = (new GalleryCategoriesModel)->findByUrl($post['url']);
if($select['clientChoice'] != null){
$tabs = json_decode($select['clientChoice'], true);
$new = $tabs + $clientChoice;
$chosen = json_encode($new);
} else {
$chosen = json_encode($clientChoice);
}
$update = (new GalleryCategoriesModel)->update(['clientChoice'=>$chosen], $post['id']);

这是我在数据库中得到的:

{"25":{"13x18":"1","20X30":"3","30x45":"5","digital":"1"},
"37":{"13x18":"4","20X30":"8","30x45":"3","digital":"2"}}

您的问题在于对array_merge的调用。来自手册:

具有数字键的输入数组中的值将在结果数组中用从零开始的递增键重新编号

因此,具有2342密钥的两个数组最终合并为:

Array
(
[0] => Array
(
[13x18] => 5
[20X30] => 5
[30x45] => 4
[digital] => 4
)
[1] => Array
(
[13x18] => 2
[20X30] => 1
[30x45] => 3
[digital] => 1
)
)

您可以通过使用数组并集运算符(+(来解决此问题,该运算符将保留两个数组中的键(尽管如果键与$tabs中已存在的键相同,它将忽略$clientChoice(,但由于它们是id值,我认为这不应发生。

$new = $tabs + $clientChoice;

在这种情况下,$new包含:

Array
(
[23] => Array
(
[13x18] => 5
[20X30] => 5
[30x45] => 4
[digital] => 4
)
[42] => Array
(
[13x18] => 2
[20X30] => 1
[30x45] => 3
[digital] => 1
)
)

3v4l.org 上的演示

最新更新