Search code examples
phpjsonlast.fm

returning json from the lastfm api


So I am trying to create a jquery/ajax autocomplete form that uses the last.fm api to autocomplete the title of a song to whatever the user is typing, the problem im having is that I can not seem to get the last fm data to return in the proper json format. this is the format that my jquery plugin (link to autocomplete) would like returned:

{
    "suggestions": [
        { "value": "United Arab Emirates", "data": "AE" },
        { "value": "United Kingdom",       "data": "UK" },
        { "value": "United States",        "data": "US" }
    ]
}

and here is essentially what im doing in my php script the returns the json to the autocomplete plugin:

                $titleName = "what's my age";
                $limit = 1;
                $results = Track::search($titleName, $limit);
                print_array($results);
                echo "<ul>";
                while ($title = $results->current()) {
                    echo $limit;
                    echo "<li><div>";
                    echo "Artist: " . $title->getArtist() . "<br>";
                    echo "Album: " . $title->getAlbum() . "<br>";
                    echo "Duration: " . $title->getDuration() . "<br>";
                    echo "getWiki: " . $title->getWiki() . "<br>";
                    echo "name: " . $title->getName() . "<br>";
                    echo "</div></li>";
                    $jsonArray['suggestions'] = array('Name'.$limit => $title->getName(), 'Artist'.$limit => $title->getArtist());
                    $limit++;
                    $title = $results->next();
                }
                echo "</ul>";
                print_array($jsonArray);
                echo json_encode($jsonArray);

the echo and print statments are just for testing, but this is what the json_encode is returning:

{"suggestions":{"Name2":"Blink vs. Jay-Z - what's my age again","Artist2":"Dj Tech1"}}

and this is what is being returned (via the echo testing):

1
Artist: Blink 1-82
Album: 
Duration: 0
getWiki: 
name: What's My Age Again?
2
Artist: Dj Tech1
Album: 
Duration: 0
getWiki: 
name: Blink vs. Jay-Z - what's my age again

so i know the code is working properly so is the sdk autocomplete etc. i also understand that am deleting the array in the while loop each time it loops through and i have not worked a fix out for that yet, but that issue aside, the json is not returning in the requested format and i can not seem to find the proper way to construct the array in order to get it in the proper format, any ideas?


Solution

  • $suggestionsArr['suggestions'] = [];
    
    foreach (range(1,3) as $key => $value) {
        array_push($suggestionsArr['suggestions'], ['name' => 'Song1', 'artist' => 'Artist1']);
    }
    
    echo json_encode($suggestionsArr);