[英]PHP loop through JSON response and insert into MySQL
对于学校项目,我想遍历 JSON 响应并将数据插入 MySQL 数据库。
JSON 响应如下所示:
{"tableID":100965,"data":[{"updated_at":1506994152000,"prices":{"unstable_reason":"LOW_SALES","unstable":true,"sold":{"avg_daily_volume":null,"last_90d":67,"last_30d":52,"last_7d":15,"last_24h":1},"max":287.5,"avg":93.52,"min":51.01,"latest":87},"image":"IMGURL","db_name":"Test-Artikel","dbID":"123456789"},{"updated_at":1506994152000,"prices":{"unstable_reason":"LOW_SALES","unstable":true,"sold":{"avg_daily_volume":null,"last_90d":67,"last_30d":52,"last_7d":15,"last_24h":1},"max":287.5,"avg":93.52,"min":51.01,"latest":87},"image":"IMGURL","db_name":"Test-Artikel","dbID":"123456789"}],"__v":0,"createdAt":"2017-03-27T09:16:48.395Z"}
每个数组都应该是 mysql 数据库中自己的一行。
目前,我可以使用以下代码从 json 文件中获取一个信息:
<?php
$url = "linktojson";
//connect to database
//$pdo = new PDO('mysql:host=localhost;dbname=...', '...', '...');
//read the json file contents
$jsondata = file_get_contents($url);
//convert json object to php associative array
$data = json_decode($jsondata, true);
echo('<pre>');
foreach ($data['data'] as $api_data) {
echo $api_data['name'] . '<br/>';
}
?>
编辑:当前代码:
$pdo = new PDO('mysql:host=localhost;dbname=XXX', 'XXX', 'XXX');
$yourJsonArray ="test.json";
$dataArray = json_decode(json_encode($yourJsonArray),true);
foreach($dataArray as $key => $value){
$image = $key['image'];
$statement = $pdo->prepare('INSERT INTO api_data (image) VALUES (?)');
$statement->execute(array($image));
}
错误消息:警告:为第 29 行 test.php 中的 foreach() 提供的参数无效
第 29 行 = foreach(上面有一些旧评论)
编辑:添加var_dump($yourJsonArray);
在 foreach 之前:
string(638) "{"tableID":100965,"data":[{"updated_at":1506994152000,"prices":{"unstable_reason":"LOW_SALES","unstable":true,"sold":{"avg_daily_volume":null,"last_90d":67,"last_30d":52,"last_7d":15,"last_24h":1},"max":287.5,"avg":93.52,"min":51.01,"latest":87},"image":"IMGURL","db_name":"Test-Artikel","dbID":"123456789"},{"updated_at":1506994152000,"prices":{"unstable_reason":"LOW_SALES","unstable":true,"sold":{"avg_daily_volume":null,"last_90d":67,"last_30d":52,"last_7d":15,"last_24h":1},"max":287.5,"avg":93.52,"min":51.01,"latest":87},"image":"IMGURL","db_name":"Test-Artikel","dbID":"123456789"}],"__v":0,"createdAt":"2017-03-27T09:16:48.395Z"}"
Warning: Invalid argument supplied for foreach() in test.php on line 30
编辑:将 $dataArray 更改为$dataArray = json_decode($yourJsonArray,true);
错误 (4x):警告:第 33 行 test.php 中的非法字符串偏移“图像”
第 33 行 = $image = $key['image'];
编辑:我丢弃了 $key Var 并得到了这个:
string(7) "tableID" string(4) "data" string(3) "__v" string(9) "createdAt"
我如何获得“数据”的元素?
像这样尝试:
$yourJsonArray = "You Json Array will come here";
//$dataArray = json_decode(json_encode($yourJsonArray),true);
$dataArray = json_decode($yourJsonArray,true);
foreach($dataArray as $key => $value){
//Here 0,1,2,3 Will be contained inside the $key variable.
//Code to insert the data comes here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.