我正在尝试将数据从外部API导入到我自己的MySQL服务器。但问题是,我想从特定字段获取值,但它只是将其设置为1或2。
这是我尝试导入的JSON对象之一的示例:
{
_index: "events",
_type: "event",
_id: "2290", **<-- THIS IS THE VALUE I WANT TO GET**
_score: null,
fields: {
genres: [
"["World Music","Dance","Theater"]"
],
name: [
"Festival Spoffin 2016"
],
start: [
"2016-08-25T11:00:00+0000"
],
venue.location: [
5.387848,
52.1563989
],
description: [
"TEXT"
],
logo: [
"URL"
],
header: [
"URL"
],
venue.country: [
"Nederland"
],
venue.city: [
"Amersfoort"
]
},
sort: [
1472122800000
]
},
但是当我运行的查询运行良好时,这里是代码:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$jsondata = file_get_contents('https://hugo.events/genre/dance/next/900/1');
$data = json_decode($jsondata, true);
$uname = '****';
$upass = '****';
$dbh = new PDO('mysql:host=localhost;dbname=wtd', $uname, $upass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "TRUNCATE TABLE dance";
$stmt = $dbh->prepare($sql);
$stmt->execute();
if (!$stmt) {
echo "Statement failed";
} else {
$statement = $dbh->prepare("INSERT INTO dance(event_id, event_name, event_date, event_country, event_genres, event_desc, event_logo, event_header_pic)
VALUES(:eventid, :name, :date, :country, :genres, :desc, :logo, :header_pic)");
$id = $data[1]['hits']['hits'][1]['_id'];
foreach ($data[1]['hits']['hits'] as $row) {
$statement->execute(array(
"eventid" => $row['_id'][0], **<-- THIS IS THE COLUMN I WANT TO PUT IT IN**
"name" => $row['fields']['name'][0],
"date" => $row['fields']['start'][0],
"country" => isset($row['fields']['venue.country']) ? $row['fields']['venue.country'][0] : '',
"genres" => $row['fields']['genres'][0],
"desc" => $row['fields']['description'][0],
"logo" => $row['fields']['logo'][0],
"header_pic" => $row['fields']['header'][0]
));
}
echo "Data inserted into dance table";
}
当我将其作为JSON回显时它只返回这个,并且在phpMyAdmin中也显示相同的内容:
{
id: "1",
event_id: "2", **<-- THIS IS SUPPOSED TO BE THE VALUE OF _ID**
event_name: "Festival Spoffin 2016",
event_date: "2016-08-25T11:00:00+0000",
event_country: "Nederland",
event_genres: "["World Music","Dance","Theater"]",
event_desc: "TEXT",
event_logo: "URL",
event_header_pic: "URL"
},
答案 0 :(得分:2)
id是一个整数,而不是一个数组,所以最后你不需要额外的[0]
。否则,你只是得到整数中的第一个数字。
"eventid" => $row['_id'],