从jSon数组获取值并执行sql插入 [英] Get values from jSon array and do sql insert

查看:216
本文介绍了从jSon数组获取值并执行sql插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的数组;

    $json = '
{
    "1":{
        "Device_ID":"a9a3346be4375a92",
        "Date":"2012-05-31",
        "Time":"15:22:59",
        "Latitude":"51.4972912",
        "Longitude":"0.1108178"
    },
    "2":{
        "Device_ID":"a9a3346be4375a92",
        "Date":"2012-05-31",
        "Time":"15:52:07",
        "Latitude":"51.4988357",
        "Longitude":"0.1222859"
    }
}';

它的解码方式如下:$array = json_decode($json);

我现在尝试将上述数组中的所有$ items插入数据库;所以我想在一条记录中存储1内的所有数据,并在第二条记录中存储2内的所有值.

I am trying to now insert into a database all the $items in the above array; so i would like to store in a single record all the data within 1, and in a second record all the values within 2.

这个想法是我永远不会知道数组的大小,所以它可能有100个$ item.

The idea is i will never know the size of the array so it could have 100 $items.

这将如何完成?

推荐答案

尝试如下操作:

$item_array = json_decode($json, true);
$insert_query = "INSERT INTO items (column1,column3) VALUES ";
$i = 0;
$array_count = count($item_array);

foreach($item_array as $item) {
 $end = ($i == $array_count) ? ';' : ',';
 $insert_query .= "('".$item['date']."','".$item['device_id']."')" . $end;
 $i ++;
}

mysql_query($insert_query);

结果查询如下所示:

INSERT INTO items (column1,column3) VALUES ('asdf',123),('asdfe',1234);

这篇关于从jSon数组获取值并执行sql插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆