繁体   English   中英

PHP循环JSon并将Json数据插入数据库

[英]PHP Loop JSon and Insert the Json Data into Database

{"details":
[{"Ticket_Date":"2014-02-20 11:32:05","Ticket_No":1950,"Amount":1.3,"In_Out":"IN","Vehicle_ID":27,"From_LocationID":3,"PriceType_ID":0,"Trip_ID":"6d744df4dfc017b1-103879384421","To_LocationID":1,"Inspector_Print ":0,"Driver_ID":16},
{"Ticket_Date":"2014-02-20 11:56:22","Ticket_No":1951,"Amount":1.3,"In_Out":"IN","Vehicle_ID":27,"From_LocationID":3,"PriceType_ID":0,"Trip_ID":"6d744df4dfc017b1-505617563631","To_LocationID":1,"Inspector_Print ":1,"Driver_ID":16}
]}

这是Json Pass to PHP,我试图使用PHP在我的数据库中插入这些数据

<?php
$data = file_get_contents("php://input");
//echo $data;
//$obj = var_dump(json_decode($data));

$json = json_decode($data);


mysql_connect("localhost", "root", "123456") or die("Could not connect");
mysql_select_db("db_shuttlebus") or die("Could not select database");

if (is_array($json)) {
    $d = array();
    foreach($json as $obj) {
        $Ticket_No = $obj->{'Ticket_No'};
        $Ticket_Date = $obj->{'Ticket_Date'};
        $Amount = $obj->{'Amount'};
        $In_Out = $obj->{'In_Out'};
        $Vehicle_ID = $obj->{'Vehicle_ID'};     
        $From_LocationID = $obj->{'From_LocationID'};
        $PriceType_ID = $obj->{'PriceType_ID'};
        $Trip_ID = $obj->{'Trip_ID'};
        $To_LocationID = $obj->{'To_LocationID'};
        $Inspector_Print = $obj->{'Inspector_Print'};
        $Driver_ID = $obj->{'Driver_ID'};
        $Updated_Time = date("Y-m-d H:i:s");
        $Route_ID = $obj->{'Route_ID'};
        //echo $_id;
        $query = "INSERT INTO tbl_ticket (Ticket_No,Ticket_Date,Amount,In_Out,Vehicle_ID,From_LocationID,PriceType_ID,Trip_ID,To_LocationID,Inspector_Print,Driver_ID,Updated_Time,Route_ID)VALUES('".$Ticket_No."','".$Ticket_Date."','".$Amount."','".$In_Out."','".$Vehicle_ID."','".$From_LocationID."','".$PriceType_ID."','".$Trip_ID."','".$To_LocationID."','".$Inspector_Print."','".$Driver_ID."','".$Updated_Time."','".$Route_ID."')";

        $rs = mysql_query($query) or die ("Error in query: $query " . mysql_error());
            if (!$rs) { 
                $d[] = array('Ticket_No' => $Ticket_No ,'Updated_Time' => $Updated_Time);
            }
    }
    $pass_json = json_encode($d);
    echo $pass_json;

}
?>

但是,我无法将$json as $obj任何数据$json as $obj ,为什么?

你应该替换你的foreach

foreach($json->details as $obj)

对于$jsonis_array将返回FALSE ,因为即使JSON有效(它看起来是这样),默认情况下json_decode返回一个对象,而不是一个数组。 这一行:

if (is_array($json)) {

...将始终返回FALSE而不执行。 要将JSON转换为关联数组,请将第二个参数传递给函数:

$json = json_decode($data, true);

在您的示例中,如果您希望保留其余代码,只需将is_array更改为is_object即可。 但是,检查JSON是否有效的更好方法是:

if(json_last_error() === JSON_ERROR_NONE) {

然后你可以处理解码对象的details参数的问题:

foreach($json->details as $obj) {

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM