Question

I'm coding an iTunes search app using the iTunes Search API. So far I have everything working properly but here is the problem I am running into. If you want to search all media types by a particular keyword it returns the results in no particular order. You may have movies, podcasts, songs, etc mixed in randomly in the results. The API, as far as I know only allows you to sort by most recent release date.

I would like to sort the results by the "kind":key to group them by media type. I don't care what particular order they are in as long as they are grouped together by media type.

This is part of a typical return in JSON format with simple key value pairs. I have it set to return the maximum results so I may have up to 200 results with 10 different media types with the key of "kind":

{"wrapperType":"track",
 "kind":"song",
 "artistId":909253,
 "collectionId":120954021,
 "trackId":120954025,
 "artistName":"Jack Johnson",

Here is part of my results array:

$iTunes = array();
for($i=0; $i<count($data['results']); $i++) {
$kind = $data['results'][$i]['kind'];
$artistId = $data['results'][$i]['artistId'];
$collectionId = $data['results'][$i]['collectionId'];
$trackId = $data['results'][$i]['trackId'];
$artistName = $data['results'][$i]['artistName'];
$trackName = $data['results'][$i]['trackName'];
$collectionName = $data['results'][$i]['collectionName'];
$artistViewUrl = $data['results'][$i]['artistViewUrl'];
$trackViewUrl = $data['results'][$i]['trackViewUrl'];
$collectionViewUrl = $data['results'][$i]['collectionViewUrl'];
$image100 = $data['results'][$i]['artworkUrl100'];
$collectionPrice = $data['results'][$i]['collectionPrice'];
$previewUrl = $data['results'][$i]['previewUrl'];

I'm trying to wrap my head around grouping by values of keys. Do I create another array and iterate over the $kind = $data['results']?

Was it helpful?

Solution

It would seem that you would need to build an array with 'kind' as a dimension. So something like this:

$data_array = array();
for ($i = 0;  $i <count($data['results']); $i++) {
    $kind = $data['results'][$i]['kind'];
    $data_array[$kind][] = $data['results'][$i];
}

You could then work with the array like this:

foreach ($data_array as $kind => $kind_array) {
    // echo out any category headers based on $kind
    foreach($kind_array as $item) {
        // echo out each individual item within this kind group
    }
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top