Web API: How to Access Arrays in Array?

Web API is an amazing application you can use to get cool and/or useful data. Basically, you have a library of data that is open to the public that you can access, process and share with other people. It could be part of your product brand (depending on license) or just enhance the outlook of your programmes.

If you have never used Web APIs before they are basically a set of data that are written in XML/JSON format which you can further process with your choice of programming language.

I thought of sharing how to access JSON data with PHP. This sample API is from Last.FM’s scrobbling API. Scrobblers are used to keep track of what you listen to on your multimedia players. I scrobble my Spotify playlist so whenever a song is played, Scrobbler will take note of the song info and updates the respective XML data.

How it Looks Like

To access Last.FM’s Web API for “listing of recenttracks” the following callback function is used. Copy, edit and paste in your browser’s URL box and run:

http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=YOUR_USERNAME&api_key=YOUR_API_KEY&limit=5&format=json

From the URL’s strings we know that it has a method name (Last.FM’s special method) called user.getrecenttracks and strings for user name, API key, limit (number of tracks to be shown) and preferred data format. Be sure to click on Collapse All and then access each array by clicks; that way it will be easier to read. Expand the tree as shown below:

You just expanded the first 2 levels of the tree. In an array it looks something like this: recenttracks(@attr(), track()). The syntax is wrong but you get the idea.

The XML Tree

This XML tree has 3 visible arrays in the picture above: recenttracks(), @attr() and track().

Now let’s expand that tree (arrays) a little bit like the example below:

Now we can finally see one of the tracks scrobbled. If it matches your current player, it works! If you only just registered for a Last.FM account (and have it connected) then you won’t see anything in it.

Access One Song (Piece of Data)

Let’s access Track 0’s song name and display it on a web page. Copy and paste the codes below in a PHP file with your choice of name. I name mine last.fm.php.

<?php

$username = YOUR_USERNAME;
$apiKey = YOUR_API_KEY;
$setLimit = 5;

$getRecTracks = json_decode(file_get_contents($root."?method=user.getrecenttracks&user=".$username."&api_key=".$apiKey."&limit=".$setLimit."&format=json"), TRUE)["recenttracks"]["track"][0]["name"];

echo $getRecTracks;

?>

You will see the the most recent track-name on the webpage! The key to accessing a specific piece of data is by accessing the XML data, and then point to the specific indexes through the arrays: [“recenttracks”][“track”][0][“name”]. Track these names in the tree shown and see if you can understand how the sequence of indexes are constructed.

When is it an Array or a Piece of Data?

If it has a branch/branches, it’s definitely an array. If it’s a “dead-end”, it belongs to a tree (array) thus making it a string-value (one piece of data).

Quick Practice

Now, try accessing artist name and album name using the concept above. Expand the artist and album branch first and see the last piece of relevant data values.

Then, copy and paste the $getRecTracks variable (rename each of them) and modify the pointed indexes at the end of the string. There should be two more variables, 1 for the artist’s name and 1 for the album name.

Echo them and make sure each variable has different names.

Did that work?

Arrays in Array

So accessing single piece of data is understood but what if you need to access all 5 indexes from track()?

Logically speaking you can copy paste the 3 variables created for track [0] and rename them accordingly. That is very inefficient especially when you need to reuse the code for example changing the $setLimit value to something higher say, 10 (most recent tracks). You can’t keep copying and pasting variables and echo them one by one.

By now you should notice the expanded song info came from the track() array with the [0] selector/index. There are 4 other indexes as well namely [1], [2], [3] and [4]. Each index comes with the same branches. All array indexes start from 0 not 1.

Note that the only differences are the indexed numbers. If you change $setLimit to 10 for example and refresh the XML page, you will begin to notice additional indexes in track(): [5], [6], [7], [8] and [9].

To access these indexes using PHP, let’s use the for() loop. But first, let’s modify the $getRecTracks variable first

<?php

$getRecTracks = json_decode(file_get_contents($root."?method=user.getrecenttracks&user=".$username."&api_key=".$apiKey."&limit=".$setLimit."&format=json"), TRUE)["recenttracks"]["track"];

?>

I reduced the index pointer to [“track”] and deleted the number and “name” strings. Full code below:

<?php

$username = YOUR_USERNAME;
$apiKey = YOUR_API_KEY;
$setLimit = 5;

$getRecTracks = json_decode(file_get_contents($root."?method=user.getrecenttracks&user=".$username."&api_key=".$apiKey."&limit=".$setLimit."&format=json"), TRUE)["recenttracks"]["track"];

for ($i=0; $i<$setLimit; $i++){
  echo "<b>SONGS:</b> " . $getRecTracks[$i]["name"];
}

?>

Since the number indexes are automated and sequential, you can use for() loop to access these indexes automatically. While the rest of the index pointers are the same for each numbered array, you can just add the desired indexes at the end:

$getRecTracks[$i]["name"]

When looped, you will access each array as follows:

...[0][song name]
...[1][song name]
...[2][song name]
...[3][song name]
...[4][song name]

No matter what the value is for $setLimit, the loop will go on accordingly until the satisfied limit is met. The limit is 50 by the way (Last.FM’s limit). A higher number will return error warnings on each illegal extra.

Practice

Do the same for artist names and album names for all set number of songs.

Live Demo

Once you have chosen the pieces of data you want to retrieve, put ’em together and format them accordingly. You can put in on your website, or make a bot for Telegram so that the bot can retrieve the list for you.

Check out my live sample of the working codes here.

Leave a Reply

Your email address will not be published. Required fields are marked *

LINKS :)

© botdroid.me since 1998. Engine by Wordpress. Custom theme. Privacy Policy. Browse comfortably please. Borrowed media credits.