kristian
kristian

Reputation: 213

How to get data from array [API/JSON]

I'm currently trying to get going with API's but i'm finding it really hard to extract the data from the api into my webpage.

I have tried using json_decode($, true), and it works OK, but some data I just cant extract.

Like, in this example, how would you get the name?

{"id":12345678,"name":"MyAwesomeLeagueName","profileIconId":593,"summonerLevel":30,"revisionDate":1389164617000}

I have used for getting data from others, but cant really get it to work with types like this one.

//put json in array 
$r = json_decode($r, true); 
echo $r['champions'][1]['attackRank'];

Also, if anyone have some good JSON -> PHP Tutorials I would really appreciate.

Upvotes: 0

Views: 5275

Answers (1)

gazareth
gazareth

Reputation: 1154

In that example to access the name you just need to refer to $r['name'] e.g.

echo $r['name'];

After decoding the JSON string, do a var_dump on your array and it will show you the contents and how to access.

To get all with a certain magic rank as per your example, you'd need to loop through the array and test the value of the particular key:

$r = json_decode($r, true);

//loop through $r
foreach ($r['champions'] as $key => $value) {
  if ($value['magicRank'] != 8) {
    //if magicRankis not 8, ignore and move on to the next entry
    continue;
  }
  //magicRank is 8, do something
  echo $value['name'] . " has magic rank of 8<br />";
}

Upvotes: 3

Related Questions