PHP如何循环JSON和提取字段[重复]
Posted
技术标签:
【中文标题】PHP如何循环JSON和提取字段[重复]【英文标题】:PHP how to loop JSON and Extract fields [duplicate] 【发布时间】:2022-01-21 00:27:18 【问题描述】:我正在使用 php 和 curl 从飞行旅行 API 中提取数据 我正在尝试从旅行 API 循环以下 JSON 输出,并尝试使用循环将“flight_date”和“airport”填充到变量中。
"pagination":
"limit": 1,
"offset": 0
,
"data": [
"flight_date": "2021-12-19",
"flight_status": "scheduled",
"departure":
"airport": "Suvarnabhumi International",
"timezone": "Asia/Bangkok"
,
"arrival":
"airport": "Seoul (Incheon)",
"timezone": "Asia/Seoul",
"iata": "ICN"
,
"airline":
"name": "Delta Air Lines"
,
"flight":
"number": "7918",
"iata": "DL7918"
"codeshared":
"airline_name": "korean air",
"airline_iata": "ke"
,
"aircraft": null,
"live": null
]
当我循环上述内容时,我不断得到数组以进行数组到字符串的转换
【问题讨论】:
提取和循环的代码在哪里?此外,您的 JSON 格式错误:"iata": "AC6123", ,
我更正了它,我错误地缩短了它,因为***不会发布这么长的代码
感谢建议的答案对我有用
【参考方案1】:
为了将 JSON 用作 PHP 数组,您实际需要做的是使用 json_decode()。
不过,您还需要首先确保您的 JSON 没有格式错误。我尝试像这样调试提供的 JSON:
$json[] = '
"pagination":
"limit": 2,
"offset": 0,
"count": 2,
"total": 315303
,
"data": [
"flight_date": "2021-12-19",
"flight_status": "scheduled",
"departure":
"airport": "Suvarnabhumi International",
"timezone": "Asia/Bangkok",
,
"arrival":
"airport": "Seoul (Incheon)",
"timezone": "Asia/Seoul",
,
"airline":
"name": "Delta Air Lines",
"iata": "DL",
"icao": "DAL"
,
"flight":
"number": "7918",
"iata": "DL7918",
,
"aircraft": null,
"live": null
,
"flight_date": "2021-12-19",
"flight_status": "scheduled",
"departure":
"airport": "Suvarnabhumi International",
"timezone": "Asia/Bangkok",
,
"arrival":
"airport": "Heathrow",
"timezone": "Europe/London",
,
"airline":
"name": "Air Canada",
"iata": "AC",
"icao": "ACA"
,
"flight":
"number": "6123",
"iata": "AC6123",
,
"aircraft": null,
"live": null
]
';
foreach ($json as $string)
echo 'Decoding: ' . $string;
json_decode($string);
switch (json_last_error())
case JSON_ERROR_NONE:
echo ' - No errors';
break;
case JSON_ERROR_DEPTH:
echo ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
echo ' - Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
echo ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
echo ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
echo ' - Unknown error';
break;
echo PHP_EOL;
看来您的 JSON 格式不正确。 您可以使用此站点:https://jsonlint.com/ 来检查您的 json 问题出在哪里。
【讨论】:
我更正了它,我错误地缩短了它,因为***不会发布这么长的代码 感谢建议的答案对我有用以上是关于PHP如何循环JSON和提取字段[重复]的主要内容,如果未能解决你的问题,请参考以下文章
BigQuery:如何从重复记录中仅提取某些字段作为另一个重复字段