Php 如何将json数组数据插入mysql?
嗨,我正在尝试将json数组插入我的MySQL数据库。使用android客户端的数组json数据Php 如何将json数组数据插入mysql?,php,android,mysql,arrays,json,Php,Android,Mysql,Arrays,Json,嗨,我正在尝试将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
{"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"
}
]
}
当您对$data进行json_解码时
它将是这样一个对象
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$数据,是真的
在此之后,您可以使用foreach将其插入db,您的$message\u data->message或$message\u data['message']MySQL代码在哪里?一旦您使用该true标志解码JSON字符串,它将只是您的普通数组。只需像平常一样对待它,使用PDO或MySQLi API进行插入,而不是解析为字符串message$message_data=json_decode$data,true;是一个数组,因此您可以执行$message_data['message'];为了让所有其他的东西都记住,您正在以文本的形式传递null-它将不会像预期的地址那样工作。
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
)
)
)