user7582130
user7582130

Reputation:

How to grab specific API data

First of all the code itself is working, the only problem being is that I cannot target a specific set of data from the API as it automatically adjust.

I had been told to set at the value after the $json, via the use of ['value here'], from here the code will take the information from the API according to which number is entered.

However, this API is self-adjusting, so the person in rank 1 might change, however, I still want to target Jimmy and not another person.

Is there any way to do this?

I was thinking:

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

But this did not work.

My PHP code.

<?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 Data:

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

Upvotes: 2

Views: 86

Answers (2)

Rajind Pamoda
Rajind Pamoda

Reputation: 143

Try this.

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

Upvotes: 0

splash58
splash58

Reputation: 26153

It will work only if all names are unique

$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

Upvotes: 1

Related Questions