php - 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"}}
解决方案
您的问题在于您对array_merge
. 从手册:
带有数字键的输入数组中的值将使用从结果数组中的零开始递增的键重新编号
所以你的两个数组的键23
和42
最终合并为:
Array
(
[0] => Array
(
[13x18] => 5
[20X30] => 5
[30x45] => 4
[digital] => 4
)
[1] => Array
(
[13x18] => 2
[20X30] => 1
[30x45] => 3
[digital] => 1
)
)
您可以使用数组联合运算+
符(发生。$clientChoice
$tabs
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
)
)
推荐阅读
- python - 确保在 N 个布尔值的 M 个随机输出中生成所有 2**N 个组合
- android - ConstraintLayout 将百分比设置为 RecyclerView 项中的 imageview 宽度和高度
- javascript - 如何在 one2many odoo 13 上触发计算
- angular - 我如何在离子选择中使用/显示这些类别
- angular - 如何将 bin 脚本添加到 Angular 的 ng-package 生成库
- arrays - 我需要创建一个有属性的类。其中之一,必须是具有属性的属性,不知道如何解释
- ios - 我们可以将 iOS 在应用购买收据中存储到我们的服务器吗
- c++ - c++ Windows 调试性能与 linux 相比非常慢
- verilog - For循环在迭代之间或之后求和吗?Verilog
- css - 为什么关键帧动画在 Safari 中不起作用