【问题标题】:Inserting Nested JSON into mySQL using Php使用 Php 将嵌套 JSON 插入 mySQL
【发布时间】: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']

标签: php mysql json pdo


【解决方案1】:

首先,你的台词:

$array_genre= $data['results']['genre'];//

没有按预期工作,因为这个键不存在。 你在

中再次使用它
foreach ($array_genre as $genrerow) { //...

你可能想要的地方:

foreach ($row['genre_ids'] as $genre_id) {

    // all the other bindings
    $stmt->bindParam(":genre",$genre_id )
}

假设您想为每种类型插入一行。否则您的数据库架构需要更多解释......这可能意味着一个新问题......

foreach($row['genre_ids'] ... 遍历该特定行的genre_ids,json_decode 为您变成了一个数组。

但是,我认为您的数据库方案可以改进。将一行变成多行通常是个坏主意,除非你有办法处理它。通常的方法是:特殊的数据库字段(数组、json)或将电影链接到流派的连接表(仅包含流派 ID 和电影 ID 或其他内容)。 - 两者都解决了标准化问题,在这一点上这可能是一个小麻烦,但很快就会变得更烦人。

【讨论】:

    猜你喜欢
    • 2017-08-23
    • 2017-08-25
    • 2017-10-29
    • 1970-01-01
    • 2018-06-19
    • 2016-04-18
    • 2011-12-05
    • 1970-01-01
    • 2020-03-04
    相关资源
    最近更新 更多