2

我正在尝试使用 PHP 将 JSON 提要中的数据导入 MySQL 数据库。

我有下面的代码,但没有得到任何地方。

我一直在获取,Connected to Database但没有从 JSON 数据中提取任何内容。

JSON 数据是使用 import.io 从提要创建的。

任何帮助表示赞赏

JSON数据在这里

    <?php

$data = file_get_contents('https://query.import.io/store/connector/e18543ae-48d1-47d3-9dc7-c3d55cab2951/_query?_user=363ec2db-fb95-413f-9a20-3fe89acbf061&_apikey=HOXvwSMX4HlmqH123i5HeELV6BwKq%2BFRInTzXc4nfl5VtP0pJyChxMT9AEiu1Ozi0vWZmUB%2BKcSsxHz2ElHNAg%3D%3D&format=JSON&input/webpage/url=http%3A%2F%2Fsports.yahoo.com%2Fgolf%2Fpga%2Fleaderboard');

$array = json_decode($data, true);
$rows = array();   

$index = 0;

foreach($array['results'] as $mydata)
    {
        print_r($mydata);
        echo "<br>";

        foreach($mydata as $key => $value)
            {
                print_r ($key);
                print_r ($value);
                echo $index;
                echo "<br><br>";
                $rows[] = "('" . $value . "')";
            }   
        echo "<br>";
        $index++;
    }

echo "<br><br><br>";
print_r ($rows);

$values = implode(",", $rows);
echo "<br><br><br>";
print_r ($values);

$hostname = 'localhost';                 // write the rest of your query
$username = 'username';
$password = 'password';

try 
{
    $dbh = new PDO("mysql:host=$hostname;dbname=database", $username, $password);
    echo 'Connected to database<br />'; // echo a message saying we have connected 
    $count = $dbh->exec("INSERT INTO import_io (total, round_1, round_2, round_3, round_4, thru, name/_source, name, today, name/_text, strokes) VALUES ($values)"); 
    echo $count;// echo the number of affected rows
    $dbh = null;// close the database connection
}
catch(PDOException $e)
{
    echo $e->getMessage();
}

?>
4

1 回答 1

1

首先,我们必须获取每一行,然后执行另一个循环来获取该行中包含的每个值,这样我们将获得一个二维数组,其中包含要格式化的数据以放入数据库中。

$i = 0;    
foreach($array['results'] as $result){
    foreach ($result as $key => $value)
        $rows[$i][] = "'" . $value . "'";
    $i++;
}

然后,在这里我们格式化数据以适合我们的查询,该查询将为之前获取的每一行执行。

try{
    $dbh = new PDO("mysql:host=$hostname;dbname=database", $username, $password);
    foreach ($rows as $row) {
        $row = implode(",",$row); //making a string from an array with each item separated by comma
        $query = "INSERT INTO import_io (total, round_1, round_2, round_3, round_4, thru, name/_source, name, today, name/_text, strokes) VALUES ($row)<br>"; 
        $count = $dbh->exec($query); 
    }
    $dbh = null;// close the database connection
}catch(PDOException $e){
    echo $e->getMessage();
}
于 2014-07-15T21:31:58.827 回答