Reputation: 653
I am trying to parse iTunes Search album/track information. The track listing comes in out of order, and when I try to order by track number, it is still slightly out of order.
For example, I am parsing this:
$url = 'https://itunes.apple.com/search?term=band+name&entity=song';
$json = file_get_contents($url);
$data = json_decode($json, true);
asort($data['results']);
if(!empty($data['results'])) {
foreach($data['results'] as $album) {
echo '<p>'.$album['trackNumber'].'. '.$album['trackName'].'</p>';
}
}
The track number result is: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 11. For some reason 12 is displaying before 11. What is the reason for this?
Any suggestions would be greatly appreciated. Thanks in advance.
Upvotes: 0
Views: 40
Reputation: 15847
In order to sort the array by the value of a specific key (trackNumber
in your case) you need to use usort
, and a comparison function (cmp
in the example below)
$url = 'https://itunes.apple.com/search?term=band+name&entity=song';
$json = file_get_contents($url);
$data = json_decode($json, true);
usort( $data['results'], 'cmp' );
if(!empty($data['results'])) {
foreach($data['results'] as $album) {
echo '<p>'.$album['trackNumber'].'. '.$album['trackName'].'</p>';
}
}
// comparison function
function cmp( $a, $b )
{
if ($a['trackNumber'] == $b['trackNumber']) {
return 0;
}
return ($a['trackNumber'] < $b['trackNumber']) ? -1 : 1;
}
Here's what you get
1. Glorious Day (feat. Kristian Stanfill)
1. New Feeling
1. Rocket Science (feat. Tyler Eads)
1. What Yo Name Iz? (Remix) [feat. Wale, Big Sean and Bun B]
2. A Clean Break (Let's Work) [Live]
2. Worthy of Your Name (feat. Sean Curran)
3. Don't Worry About the Government
3. How Great Is Your Love (feat. Kristian Stanfill)
4. Pulled Up
4. Build My Life (feat. Brett Younker)
[...]
Note you have more tracks with the same track number.
That's because the results you get are tracks from different albums.
You may need to filter your results before sorting or improve the comparison function.
Upvotes: 2