php - 我如何从下面的 json 对象中为我的数据库在 php 中获取这个 json 值standing_place
问题描述
JSON:
{
"success": 1,
"result": {
"total": [
{
"standing_place": "1",
"standing_place_type": "Promotion - NBA (Play Offs)",
"standing_team": "Toronto Raptors",
"standing_P": "82",
"standing_W": "59",
"standing_WO": "0",
"standing_L": "23",
"standing_LO": "0",
"standing_F": "9156",
"standing_A": "8518",
"standing_PCT": "0.720",
"team_key": "51",
"league_key": "787",
"league_season": "2017/2018",
"league_round": "Eastern Conference",
"standing_updated": "2018-05-28 17:22:59"
},
{
"standing_place": "3",
"standing_place_type": "Promotion - NBA (Play Offs)",
"standing_team": "Philadelphia 76ers",
"standing_P": "82",
"standing_W": "52",
"standing_WO": "0",
"standing_L": "30",
"standing_LO": "0",
"standing_F": "9004",
"standing_A": "8635",
"standing_PCT": "0.634",
"team_key": "56",
"league_key": "787",
"league_season": "2017/2018",
"league_round": "Eastern Conference",
"standing_updated": "2018-05-28 17:23:00"
}
]
}
PHP:
$APIkey='XXXXXXX';
$leagueId = 787;
$curl_options = array(
CURLOPT_URL => "https://allsportsapi.com/api/basketball/?met=Leagues&APIkey=$APIkey&leagueId=$leagueId",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_TIMEOUT => 30,
CURLOPT_CONNECTTIMEOUT => 5
);
$curl = curl_init();
curl_setopt_array( $curl, $curl_options );
$result = curl_exec( $curl );
$result = (array) json_decode($result);
var_dump($result);
$result = json_decode($result);
foreach($result as $mydata)
{ foreach($result->result as $myresult)
{
foreach($myresult->total as $total)
{
$standing_place_type = $total->standing_place_type;
}
}
}
此 Json 代码来自我与其他一些 Api 合作过的所有运动 APi 的源代码,但没有发现使用此代码很有趣。我已经尝试了我知道的所有方法来解决这个问题,但所有方法都证明是无效的,结果是空的。如果您在帮助之前使用过 api,或者如果您知道我该如何解决这个问题,请帮忙
解决方案
首先,如果您比 JSON 表示法更熟悉 PHP,请尝试查看结构转换print_r
的结果。json_decode
它应该是这样的:
$decodedJson = json_decode($json);
print_r($decodedJson);
// Result
stdClass Object
(
[success] => 1
[result] => stdClass Object
(
[total] => Array
(
[0] => stdClass Object
...
你能看到吗你能明白吗?它是一个对象,带有一个结果对象,带有一个带有对象数组的总对象。
现在,知道您可以访问这样的 PHP 对象公共属性以及可以在示例中使用的$myObject->my_property
数组,您可以foreach
像这样在 PHP 中导航这个结构:
// Check if the object contains the expected structure
if ($decodedJson && isset($decodedJson->result) && isset($decodedJson->result->total)) {
// Iterate over Total Array
foreach ($decodedJson->result->total as $total) {
// Print values
echo "Standing_Place: {$total->standing_place} / Standing_Place_Type: {$total->standing_place_type}." . PHP_EOL;
}
}
活样。
Obs:在您发布的 JSON 中,最后缺少一个大括号。您可以验证此站点的 json 。
推荐阅读
- java - Logback - 使用多个实例
- php - “找不到”和“SQLSTATE[HY000] [2002]”错误
- java - 谷歌云 SDK java.nio.file.InvalidPathException
- python-3.x - Django 中的 PyGithub;ModuleNotFoundError
- python - 什么是详细输出?
- scala - Scala 将 Json 读取为 Map[String,T]
- c - 无法获得点积 C 编程的结果
- javascript - 在 JavaScript 中使用 class/id 编辑 innerHtml 不起作用
- java - 在 Windows 的 Sublime Text 上运行 Java
- numpy - 内存泄漏(cython + numpy)