我试图从json文件向表中插入数据,但行得到0.而不是来自json的值
JSON代码:
{
"posts": [{
"dr_DeviceID": "323",
"dr_UserLocalLat": "38.7482572",
"dr_UserLocalLong": " -9.1847516"
}]
}
$connection = mysql_connect("localhost", "***", "!*****!");
if (!$connection)
{
die('PHP Mysql database connection could not connect : ' . mysql_error());
}
$db_selected = mysql_select_db("*****", $connection);
$result=mysql_query("SELECT * FROM $tbl_name wHERE ad_IMEI=ad_IMEI ");
$i=0;
while($row=mysql_fetch_array($result)) {
$response[$i]['dr_DeviceID'] = $row['ad_IDDevice'];
$response[$i]['dr_UserLocalLat']= $row['user_location_lat'];
$response[$i]['dr_UserLocalLong']= $row['user_location_long'];
$data['posts'][$i] = $response[$i];
$i=$i+2;}
$json_string = json_encode($data);
$file = 'select.json';
file_put_contents($file, $json_string);
$jsondata = file_get_contents('select.json');
$obj = json_decode($jsondata, true);
$id = $obj['posts']['dr_DeviceID'];
$dr_UserLocalLat = $obj['posts']['dr_UserLocalLat'];
$dr_UserLocalLong = $obj['posts']['dr_UserLocalLong'];
$sqlj = "INSERT INTO $tbl_name1 (dr_DeviceID, dr_UserLocalLat, dr_UserLocalLong) VALUES('$dr_DeviceID', '$dr_UserLocalLat', '$dr_UserLocalLong')";
$result=mysql_query($sqlj,$connection);
答案 0 :(得分:2)
问题是你正在尝试访问一个对象数组,就像它是一个对象一样。
这条线就在这里
$data['posts'][$i] = $response[$i];
你在$ data ['posts']数组中添加了一个项目。如果您的结果有多行,那么您上面留下的json示例将是
{
"posts": [{
"dr_DeviceID": "323",
"dr_UserLocalLat": "38.7482572",
"dr_UserLocalLong": " -9.1847516"
},
{
"dr_DeviceID": "324",
"dr_UserLocalLat": "39.7482572",
"dr_UserLocalLong": " -19.1847516"
}]
}
因此,当您在之后解码json时,会得到一个对象数组。要访问数组中的每个项目,您需要一些循环周期。否则,要从json获取第一个项目,您需要执行
$obj['posts'][0]['dr_UserLocalLat'], instead of $obj['posts']['dr_UserLocalLat']
。