使用PHP将嵌套的Json数组导入Mysql [关闭]

使用PHP将嵌套的Json数组导入Mysql [关闭]

问题描述:

This is my first time working with json, just playing around with some data.

This is part of my json

Array
(
    [DataSet] => Array
        (
            [Table] => Array
                (
                    [0] => Array
                        (
                            [Driver] => John Doe
                            [Shift Date] => 2018-01-05T00:00:00-05:00

I want to be able to get all the [Driver] and [Shift Date] fields and put them into a table. It has 2 columns Driver and ShiftDate, not sure where I go from here.

After lots of googling I have come up with the solution, and I apologize if I didn't word my question right this is my first crack at this, but I figured posting the answer may help someone else trying to figure this out:

$str = file_get_contents('./cgapi.json');
$json = json_decode($str, true);
foreach($json['DataSet']['Table'] as $item) {
    $stmt = $dbcon->prepare("INSERT INTO DriverData (DriverName, ShiftDate, Minutes, Stops, Gallons) VALUES (?,?,?,?,?)");
    $stmt->bind_param("sssss", $item['Driver'], $item['Shift Date'], $item['Minutes'], $item['Stops'], $item['Gallons']);
    $stmt->execute();
    $stmt->close();  
}

$drivers = array_column('Driver', $yourData);

$dates = array_column('Shift Date', $yourData);

Array column extracts all the values of the key provided as the first argument.

http://php.net/manual/en/function.array-column.php