【发布时间】:2018-12-29 16:21:49
【问题描述】:
我正在尝试将从 tmdb API 接收的嵌套 JSON 数据插入我的 mySQL 数据库。
我已经知道如何插入嵌套 JSON,但由于我需要创建的新记录将具有多对多关系(电影和电影类型),我假设我必须插入多行具有相同数据与不同的电影类型。
我一直在尝试对电影类型使用另一个 foreach 循环,但没有成功。非常感谢您的帮助。
<?php
$api = "https://api.themoviedb.org/3/movie/popular?api_key=<<api-key>>&language=en-US&page=1";
$jsondata = file_get_contents($api);
//now you have result as associative array
$data = json_decode($jsondata, true);
$array_data = $data['results'];
$array_genre= $data['results']['genre'];//
include "indexmoviedb.php";
$stmt=$db->prepare("INSERT INTO movie VALUES(:title,:poster_path,:backdrop_path,:rating,:overview,:genre)");
foreach($array_data as $row){
foreach ($array_genre as $genrerow) {// I'm assuming I have to do something like this
$stmt->bindParam(":title",$row['title'] );
$stmt->bindParam(":poster_path",$row['poster_path'] );
$stmt->bindParam(":backdrop_path",$row['backdrop_path'] );
$stmt->bindParam(":rating",$row['vote_average'] );
$stmt->bindParam(":overview",$row['overview'] );
$stmt->bindParam(":genre",$row['genres_ids'][] );// what goes in here?
$stmt->execute();
}
}
?>
这是我要插入的 json 文件
{
"results": [{
"id": 351286,
"vote_average": 6.6,
"title": "Jurassic World: Fallen Kingdom",
"popularity": 228.669,
"poster_path": "/c9XxwwhPHdaImA2f1WEfEsbhaFB.jpg",
"genre_ids": [
28,
12,
878
],
"backdrop_path": "/gBmrsugfWpiXRh13Vo3j0WW55qD.jpg"
}]
}
【问题讨论】:
-
json 中的方括号表示一个数组。与数组的 PHP 定义不同,它是按整数索引的。所以你需要把
$data['results']['genre']改成$data['results'][0]['genre']