简体   繁体   中英

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.

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

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 />";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM