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

时间:2014-02-28 17:46:04

标签: php json

{"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获取任何数据,为什么?

2 个答案:

答案 0 :(得分:2)

您应该用

替换您的foreach
foreach($json->details as $obj)

答案 1 :(得分:0)

is_arrayFALSE返回$json,因为即使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) {

然后您可以解决已解码对象的详细信息参数问题:

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