插入 SQL 时保留 JSON 数据的顺序
Posted
技术标签:
【中文标题】插入 SQL 时保留 JSON 数据的顺序【英文标题】:Preserve order of JSON data when inserting into SQL 【发布时间】:2020-01-16 18:47:37 【问题描述】:我有多个使用 jquery 序列化的输入字段,然后使用 AJAX 调用将数据保存到我的 SQL 数据库中。当我序列化输入字段时,序列化的 JSON 数据的顺序如下所示:
[
"value1": [ "123", "111", "222", "333" ],
"value2": [ "111", "222", "333", "444" ],
"value3": [ "1111", "2222", "3333", "4444" ],
"title1": [ "This is a title" ],
"title2": [ "Another title" ]
]
虽然我希望它是这样的:
[
"value1": [ "123", "111", "222", "333" ] ,
"title1": "This is a title" ,
"value2": [ "111", "222", "333", "444" ] ,
"title2": "Another title" ,
"value3": [ "1111", "2222", "3333", "4444" ]
]
序列化代码的行如下所示:
var inputVals = $(this).closest('.blockContent').find("select, textarea, input").serialize();
将数组编码为 JSON 格式的 php 代码:
parse_str($request->inputVals,$inputVals);
$inputVals = array($inputVals);
$inputVals = json_encode($inputVals);
被序列化的输入示例:
<input name="value1[0]" value=" $jsonValues['value1'][0] " type="number">
<input name="value1[1]" value=" $jsonValues['value1'][1] " type="number">
<input name="title1" value=" $jsonValues['value1'] " type="text">
更新:
为了以更好的方式提出我的问题,我如何从 Jquery/javascript 中使上面的输入字段变得像 JSON 结构一样,格式可以像我在上面的 JSON 代码中想要的那样排序?
【问题讨论】:
【参考方案1】:JavaScript(以及 JSON)对象是无序的。真的没有区别
[
"value1": [ "123", "111", "222", "333" ],
"title1": [ "This is a title" ],
"value2": [ "111", "222", "333", "444" ],
"title2": [ "Another title" ],
"value3": [ "1111", "2222", "3333", "4444" ]
]
和
[
"title1": [ "This is a title" ],
"value2": [ "111", "222", "333", "444" ],
"value3": [ "1111", "2222", "3333", "4444" ]
"value1": [ "123", "111", "222", "333" ],
"title2": [ "Another title" ],
]
但是,数组是有序的。如果您可以将数据结构更改为类似
[
"value1": [ "123", "111", "222", "333" ],
"title1": [ "This is a title" ]
,
"value2": [ "111", "222", "333", "444" ],
"title2": [ "Another title" ]
,
"value3": [ "1111", "2222", "3333", "4444" ],
"title3": "..."
]
您会发现订单被保留。 (每个对象可能首先有它们的value
或title
,但每个值和标题都会一起出现。)
【讨论】:
是的,这就是我所理解的,但我正在努力使用 serialize() 来获得该结构,任何想法我将如何重做代码以使结构像这样或我写的最后一个块我的问题? 请编辑您的问题并向我们展示$jsonValues
的全部价值。以上是关于插入 SQL 时保留 JSON 数据的顺序的主要内容,如果未能解决你的问题,请参考以下文章