简体   繁体   中英

Inserting JSON into MySQL Database

Firstly, here's an example of the JSON I have;

[["AAL.L","Anglo American plc"],["ABF.L","Associated British Foods plc"],
["ADM.L","Admiral Group plc"],["ADN.L","Aberdeen Asset Management PLC"]]

I'm trying to get create a loop to loop through the JSON and enter it into my MySQL database. The database has the following tables:

ID, Symbol, Company, Timestamp

ID is used as an auto_increment, and timestamp makes use of NOW() in the MySQL statement. The issue I'm having is that all the examples I've looked at decode JSON as a key/value pair and my JSON isn't. The examples I've been looking at are the following:

mysql_query("INSERT INTO suspiciousactivity (ID,Notes)
VALUES ('".$arr[0]['a']."','".$arr[0]['b']."')")or die(mysql_error());

I'm not asking for the code to be written for me, but just an idea of what to research into.

Your JSON is just a list of lists, so you can just do something like:

<?php


$json ='[["AAL.L","Anglo American plc"],["ABF.L","Associated British Foods plc"],
["ADM.L","Admiral Group plc"],["ADN.L","Aberdeen Asset Management PLC"]]';

$items = json_decode($json); //Here items is an array of arrays

foreach($items as $item) {
    echo $item[0]; //Symbol
    echo $item[1]; //Company
    //Here would be a good place to do your insert
}

?>

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