Reputation: 8362
Here is my array;
$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"
}
}';
It's decoded like this: $array = json_decode($json);
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.
The idea is i will never know the size of the array so it could have 100 $items.
How would this be done?
Upvotes: 2
Views: 4373
Reputation:
Try something like this:
$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);
The resulting query will look something like:
INSERT INTO items (column1,column3) VALUES ('asdf',123),('asdfe',1234);
Upvotes: 4