I have a website where my database is set up with differen开发者_开发问答t artists and song titles within the same row, where it might look this:
artist: The Monkees, title: I'm A Believer
artist: The Monkees, title: Daydream Believer
artist: The Hollies, title: The Air That I Breathe
artist: The Hollies, title: Bus Stop
artist: The Beatles, title: Hello, Goodbye
artist: The Beatles, title: Yellow Submarine
And I have an autocomplete widget set up with my site's search form that is fed a json_encoded array filled with 'artist' values.
The first problem is that if a user were to begin typing "the" into the search form, values would come up like this:
The Monkees
The Monkees The Hollies The Hollies The Beatles The BeatlesSo I used the array_unique function to remove duplicate values, but it seems that even if a value has one duplicate word (this case being "the"), it is removed entirely, so only the first value is returned:
The Monkees
Where the output I would like to have would be:
The Monkees
The Hollies The BeatlesSo, what might be another way I can remove these duplicate values and display them the way I would like?
EDIT:
Here is my source code:
<?php
include 'includes/config.php';
$return_arr = array();
$term = ($_GET['term']);
if ($con)
{
$artist = mysql_query("SELECT * FROM songs WHERE artist LIKE '%$term%' LIMIT 0, 5");
while ($row = mysql_fetch_array($artist, MYSQL_ASSOC)) {
$row_array['value'] = strtolower($row['artist']);
array_push($return_arr,$row_array);
}
}
mysql_close($con);
echo json_encode(array_unique($return_arr));
?>
array_unique
uses a strict comparison. So differences in case and whitespace are taken into consideration. Since all of those values seem to be strings, it's likely the reason why array_unique
is not working the way you would expect.
Your database structure makes it pretty difficult to weed out duplicates. I would suggest refactoring it into a table of artists and a table of songs, where songs simply reference the id of artist. This will give you a better chance of being able to keep your artist list unique.
Also, one thing I would do for your autocomplete is set it up to ignore certain strings. ('a', 'an', 'the') These are known as stopwords, and help search results be more relevant by not performing a search on common words.
精彩评论