【发布时间】:2014-04-16 22:55:02
【问题描述】:
抱歉,标题太长了。我花了一个小时,但我终于得到了这个工作。我的问题是,是否有更快、更有效的方式来做我正在做的事情。
基本上,我有一个 HTML 文本输入字段,它使用 jQuery 填充自动完成下拉答案(在本例中,是我收藏的歌曲列表的艺术家)。我之前让它运行得很顺利,直到我发现它显示了一些我喜欢的不止一首歌的艺术家的重复。所以我需要使用 array_unique() 来消除重复项。
不幸的是,我的列表不是来自 MySQL 结果的数组形式,而只是一个字符串。在摆弄了一段时间后,我让它显示在一个数组中,但现在这弄乱了我对 jQuery 列表的格式。 array_walk() 帮助我格式化数组中的每个项目,然后将其转换为字符串。这似乎是很多工作。我可以用更少的步骤完成吗?
这是我的代码:
<input type="text" class="span3" style="margin: 0 auto; " autocomplete="off" name="artist" data-provide="typeahead" data-items="4" data-source='[<?
$artistlist = "SELECT * FROM songs where id >= 0";
$result = $mysqli->query($artistlist);
while( $row = mysqli_fetch_assoc($result)) {
$artists[] = "\"".$row['artist']."\",";
//have to format this way for the jQuery results.
$artists = array_unique($artists);
}
function formatArtists(&$artists) {
$artists = str_replace("'", "'", $artists);
//have to do this because of "O'" names.
}
array_walk($artists, "formatArtists");
foreach($artists as $artist) {
$artistSelect .= $artist;
}
$artistSelect = substr(trim($artistSelect), 0, -1);
//I have to convert the array to a string so that I can trim the final comma from the list of artists. Otherwise the autocomplete breaks.
echo $artistSelect;
?>]'>
感谢您的帮助,如果您发现任何其他效率低下的地方,我还在学习中,所以我不介意纠正!
【问题讨论】:
-
首先尝试使用 SELECT DISTINCT 艺术家 FROM id >= 0 的歌曲 - 此查询将为您提供没有重复的艺术家列表。
标签: javascript php jquery mysql arrays