简体   繁体   中英

API-call JSON into MySQL

I'm working on a research project where we want to insert a JSON file (from an API-call) into a mysql database. I found multiple examples but I don't know where to begin because there are multiple objects and arrays. A second problem is that the columns and rows are separate arrays (I think?).

Our goal is to fill (daily, hourly, etc) a database that looks likes this (it is an example and we do have multiple items):

-----------------------------------
| Date | Value2 | Value3 | Value4 |
-----------------------------------
| 01-01-2015 | 123 | 1234 | 12345 |
-----------------------------------
| 02-01-2015 | 343443 | 4w3543422 | fref4rw4 | 
-----------------------------------
| 03-01-2015 | 234422r | wrfrw3434 | 2432rfr42324 |
-----------------------------------

Question is how can I get those values from the JSON (which isn't static: sometimes there will be seven days, sometimes less and sometimes more)? Where to begin?

Code from @Marmik did the trick!

<?php
$array = json_decode($json_data,true);
$sql_inserts = array();
foreach($array['reportitem']['rows']['r'] AS $row)
    {
        $sql_inserts[] = "('".$row[c][0]."','".$row[c][1]."','".$row[c]    [2]."','".$row[c][3]."')";
    }
$insert_values = implode("'",$sql_inserts);
$sql = "INSERT INTO table_name (date,Value2,Value3,Value4) $insert_values         ;";
?>

I think using foreach loop after decoding the JSON to PHP Array it can be worked out.

<?php
$array = json_decode($json_data,true);
$sql_inserts = array();
foreach($array['reportitem']['rows']['r'] AS $row)
    {
        $sql_inserts[] = "('".$row[c][0]."','".$row[c][1]."','".$row[c][2]."','".$row[c][3]."')";
    }
$insert_values = implode("'",$sql_inserts);
$sql = "INSERT INTO table_name (date,Value2,Value3,Value4) $insert_values ;";
?>

And this SQL statement is created by JSON array's data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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