如何获取特定的API数据

时间:2018-01-07 14:09:06

标签: php html arrays json api

首先,代码本身正在运行,唯一的问题是我无法在自动调整时从API中定位一组特定数据。

我被告知要设置$ json之后的值,通过使用[' value here'],此处代码将根据输入的数字从API获取信息

然而,这个API是自我调整的,所以排名1的人可能会改变,但是,我仍然想要定位吉米而不是另一个人。

有没有办法做到这一点?

我在想:

$jimmy = $json["jimmy"]["rank"]; #Grab the values.

但是这没用。

我的PHP代码。

<?php
$url = "linktotheapiishere"; #Grab API Data.
$json = json_decode(file_get_contents($url), true); #Read the API contents.
$jimmy = $json[0]["rank"]; #Grab the values.
echo $jimmy;  #Print the values.
?>

API数据:

[
{
"id": "sample1", 
"name": jimmy", 
"rank": "1", 
}, 
{
"id": "sample2", 
"name": "john", 
"rank": "2", 
}, 
{
"id": "sample2", 
"name": "bob", 
"rank": "3", 
}
]

2 个答案:

答案 0 :(得分:1)

仅当所有名称都是唯一的

时才会起作用
$json = json_decode(file_get_contents($url), true); #Read the API contents.
// make name value as key of the array
$json = array_column($json, null, 'name');
$jimmy = $json['sample2']["rank"]; #Grab the values.
echo $jimmy;  #Print the values

答案 1 :(得分:0)

试试这个。

<?php
$xml = file_get_contents("linktotheapiishere");
$json_data = json_decode($xml, true);
$jimmy = $json_data[0]["rank"];
?>
相关问题