所以我正在尝试创建一个jquery / ajax自动完成表单,它使用last.fm api自动完成歌曲的标题,无论用户输入什么,我遇到的问题是我似乎无法获得最后一个fm数据以适当的json格式返回。这是我的jquery插件(link to autocomplete)要返回的格式:
{
"suggestions": [
{ "value": "United Arab Emirates", "data": "AE" },
{ "value": "United Kingdom", "data": "UK" },
{ "value": "United States", "data": "US" }
]
}
这里基本上是我在我的php脚本中执行的操作将json返回到自动完成插件:
$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);
echo和print语句仅用于测试,但这是json_encode返回的内容:
{"suggestions":{"Name2":"Blink vs. Jay-Z - what's my age again","Artist2":"Dj Tech1"}}
这就是返回的内容(通过回声测试):
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
所以我知道代码工作正常所以是sdk自动完成等等。我也明白,每次循环时都会删除while循环中的数组,而我还没有解决这个问题,但是那个问题除此之外,json没有以请求的格式返回,我似乎无法找到构建数组的正确方法,以便以正确的格式,任何想法得到它?
答案 0 :(得分:1)
$suggestionsArr['suggestions'] = [];
foreach (range(1,3) as $key => $value) {
array_push($suggestionsArr['suggestions'], ['name' => 'Song1', 'artist' => 'Artist1']);
}
echo json_encode($suggestionsArr);