将嵌套的json数组插入数据库

时间:2016-01-13 10:29:21

标签: php

我正在尝试将JSON数组插入我的mysql数据库。这里我给出了

的格式
array ${
    "customer_id": "1",
    "products":[ {
        "product_id": "1",
        "product_qty": "2"
    }, {
        "product_id": "2",
        "product_qty": "4"
    }, {
        "product_id": "3",
        "product_qty": "12"
    }, {
        "product_id": "4",
        "product_qty": "22"
    }],
    "order_totalamount": "100"
}

我尝试了如下插入查询:

foreach($data as $item) {

            //insert into mysql table
             $sql = "insert into `order`(cm_id,product_id,product_quantity,order_totalamount,order_id,order_date) values ($cus_id,$item[product_id],$item[product_qty],$order_totalamount,$cus_id,CURDATE())";

还解码JSON数据和foreach循环

2 个答案:

答案 0 :(得分:0)

json_decode字符串并遍历产品数组并逐个插入。

$data = json_decode($json_string);
$customer_id = $data->customer_id;

foreach($data->products as $product) // its a array of products you showed in json 
{
    // insert code here for mysql insert
}

答案 1 :(得分:0)

尝试以下代码:

$res = '{
"customer_id": "1",
"products":[ {
    "product_id": "1",
    "product_qty": "2"
}, {
    "product_id": "2",
    "product_qty": "4"
}, {
    "product_id": "3",
    "product_qty": "12"
}, {
    "product_id": "4",
    "product_qty": "22"
}],
"order_totalamount": "100"
}';

$data=json_decode($res);
foreach ($data->products as $item)
$sql = "insert into `order`(cm_id,product_id,product_quantity,order_totalamount,order_id,order_date    ) values ($data->customer_id,$item->product_id,$item->product_qty,$data->order_totalamount,$data->customer_id,CURDATE())";