gpt4 book ai didi

javascript - 从 MySQL 查询到 PHP 数组的 jQuery 自动完成/提前输入

转载 作者:行者123 更新时间:2023-11-29 08:07:51 24 4
gpt4 key购买 nike

抱歉,标题太长了。我花了一个小时,但我终于成功了。我的问题是是否有一种更快、更有效的方法来完成我在这里所做的事情。

基本上,我有一个 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;
?>]'>

感谢您的帮助,如果您发现任何其他效率低下的地方,我仍在学习,因此我不介意纠正!

最佳答案

一些建议:

在获取查询结果时,您应该调用 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
?>]'>

关于javascript - 从 MySQL 查询到 PHP 数组的 jQuery 自动完成/提前输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22357744/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com