首页 > 解决方案 > JSON 数据库更新丢失键值

问题描述

我在我的数据库中得到了这个(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"}}

标签: phparraysjsondatabase

解决方案


您的问题在于您对array_merge. 从手册

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

所以你的两个数组的键2342最终合并为:

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

您可以使用数组联合运算+符(发生。$clientChoice$tabsid

$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 上的演示


推荐阅读