【问题标题】:jQuery Autocomplete/Typeahead from MySQL Query to PHP Array从 MySQL 查询到 PHP 数组的 jQuery Autocomplete/Typeahead
【发布时间】: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("'", "&#39;", $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


【解决方案1】:

只是一些建议:

在获取查询结果时,您应该调用 formatArtists,而不是在 $artists 之间循环

你可以使用一个简单的技巧来避免艺术家重复使用艺术家的名字作为数组键

有一个名为 implode() 的 php 函数可以避免一些行。

全部应用:

<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);
$artists = array();
while( $row = mysqli_fetch_assoc($result)) {
    $artist_name = '"'.formatArtists($row['artist']).'"';
    $artists[$artist_name] = $artist_name;
}
echo implode(',',$artists);//Will join every element from array using , character
?>]'>

【讨论】:

  • 那么如果我这样做,我还需要 formatArtists 函数吗?我可以直接将它应用到 $artist_name 吗?
  • 如果您将$artist_name = '"'.formatArtists($row['artist']).'"'; 替换为$artist_name = '"'.str_replace("'", "&amp;#39;",$row['artist']).'"';,那么您是对的
猜你喜欢
  • 1970-01-01
  • 2011-03-25
  • 1970-01-01
  • 2012-02-16
  • 2012-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多