gpt4 book ai didi

php - 如何将json数组数据插入mysql?

转载 作者:行者123 更新时间:2023-11-30 22:44:30 24 4
gpt4 key购买 nike

您好,我正在尝试将 json 数组插入到我的 MySQL 数据库中。使用来自 android 客户端的数组 json 数据。

{"message":[ {"body":"Fdsa","_id":"114","status":"-1","address":"null","read":"1","type":"3","date":"1429781969573","thread_id":"2"},{"body":"wtf2","_id":"113","status":"0","address":"0123456789","read":"1","type":"1","date":"1429590050090","thread_id":"1"}, {"body":"wtf2","_id":"112","status":"0","address":"0123456789","read":"1","type":"1","date":"1429590050090","thread_id":"1"}]}

如何将json数据解析到数据库中?

$message_data = json_decode($data,true);

printf($message_data['message']);die;

最佳答案

您的数据:

{
"message": [
{
"body": "Fdsa",
"_id": "114",
"status": "-1",
"address": "null",
"read": "1",
"type": "3",
"date": "1429781969573",
"thread_id": "2"
},
{
"body": "wtf2",
"_id": "113",
"status": "0",
"address": "0123456789",
"read": "1",
"type": "1",
"date": "1429590050090",
"thread_id": "1"
},
{
"body": "wtf2",
"_id": "112",
"status": "0",
"address": "0123456789",
"read": "1",
"type": "1",
"date": "1429590050090",
"thread_id": "1"
}
]
}

当你json_decode($data)

它将是一个像这样的对象

stdClass Object
(
[message] => Array
(
[0] => stdClass Object
(
[body] => Fdsa
[_id] => 114
[status] => -1
[address] => null
[read] => 1
[type] => 3
[date] => 1429781969573
[thread_id] => 2
)

[1] => stdClass Object
(
[body] => wtf2
[_id] => 113
[status] => 0
[address] => 0123456789
[read] => 1
[type] => 1
[date] => 1429590050090
[thread_id] => 1
)

[2] => stdClass Object
(
[body] => wtf2
[_id] => 112
[status] => 0
[address] => 0123456789
[read] => 1
[type] => 1
[date] => 1429590050090
[thread_id] => 1
)

)

)

但是如果你这样做json_decode($data, true)

Array
(
[message] => Array
(
[0] => Array
(
[body] => Fdsa
[_id] => 114
[status] => -1
[address] => null
[read] => 1
[type] => 3
[date] => 1429781969573
[thread_id] => 2
)

[1] => Array
(
[body] => wtf2
[_id] => 113
[status] => 0
[address] => 0123456789
[read] => 1
[type] => 1
[date] => 1429590050090
[thread_id] => 1
)

[2] => Array
(
[body] => wtf2
[_id] => 112
[status] => 0
[address] => 0123456789
[read] => 1
[type] => 1
[date] => 1429590050090
[thread_id] => 1
)

)

)

之后,您可以使用 foreach 您的 $message_data->message$message_data['message']

将其插入到数据库中

关于php - 如何将json数组数据插入mysql?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30021966/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com