我想在JSON数组中输入一些包含在数据库中的细节。
以下是我的源代码。
这是我的txt文件中的数据json数组
{
" reader_name":" Biboy Pogi",
" MAC_ADDRESS":" 00:16:25:10:7E:85&#34 ;,
" tag_reads":[
{
" antennaPort":1,
" EPC":" 2015031687850100010105B5&#34 ;,
" TID":" E280110520005A8B952F0886&#34 ;,
" isHeartBeat":假
}
]
}
{
" reader_name":" Biboy Pogi",
" MAC_ADDRESS":" 00:16:25:10:7E:85&#34 ;,
" tag_reads":[
{
" antennaPort":1,
" EPC":" 2015031687850100010105B5&#34 ;,
" TID":" E280110520005A8B952F0886&#34 ;,
" isHeartBeat":假
}
]
}
答案 0 :(得分:0)
你的json似乎是个问题。
试试这个:
[
{
"reader_name": "Biboy Pogi",
"mac_address": "00:16:25:10:7E:85",
"tag_reads": [
{
"antennaPort": 1,
"epc": "2015031687850100010105B5",
"tid": "E280110520005A8B952F0886",
"isHeartBeat": false
}
]
},
{
"reader_name": "Biboy Pogi",
"mac_address": "00:16:25:10:7E:85",
"tag_reads": [
{
"antennaPort": 1,
"epc": "2015031687850100010105B5",
"tid": "E280110520005A8B952F0886",
"isHeartBeat": false
}
]
}
]
答案 1 :(得分:0)
你JSON
错了,两次相同。也许你会这样需要它,但是这一个
{
"reader_name": "Biboy Pogi",
"mac_address": "00:16:25:10:7E:85",
"tag_reads": [
{
"antennaPort": 1,
"epc": "2015031687850100010105B5",
"tid": "E280110520005A8B952F0886",
"isHeartBeat": false
}
]
}
你无法以$antennaPort = $data['antennaPort'];
的方式到达那里。你必须这样称呼它
$antennaPort = $data['tag_reads']['antennaPort'];
$epc= $data['tag_reads'][0]['epc'];
$tid= $data['tag_reads'][0]['tid'];
像这样插入你的数据库
mysqli_query($con,$sql)
之后,你应该检查错误
if(!mysqli_query($con, $sql))
die ('Error in query: ' . mysqli_error($con));
或者你排成一行
mysqli_query($con, $sql) or die(mysqli_error());
答案 2 :(得分:0)
假设您的数据源是每行一个json。您可以使用以下示例代码执行迭代插入:
$fn = 'debug.txt';
$raw = file_get_contents($fn);
$raw = explode("\r\n", $raw);
foreach($raw as $row){
//force it to array for single item
if (substr($row, 0, 1) != '[')
$row = '[' . $row . ']';
$data_arr= json_decode($row, true);
foreach ($data_arr as $data){
$reader_name = $data['reader_name'];
$mac_address = $data['mac_address'];
$antennaPort = $data['tag_reads'][0]['antennaPort'];
$epc = $data['tag_reads'][0]['epc'];
$tid = $data['tag_reads'][0]['tid'];
$sql = "INSERT INTO tags(reader_name, mac_address, antennaPort, epc, tid)
VALUES('$reader_name', '$mac_address', '$antennaPort', '$epc', '$tid')";
if(!mysqli_query($con, $sql))
{
die('Error : ' . mysqli_error($con));
}
}
}