gpt4 book ai didi

php - 在php中从数据库中提取前三项

转载 作者:行者123 更新时间:2023-11-29 12:26:22 25 4
gpt4 key购买 nike

我正在尝试从数据库中提取流派列表。我在数据库中输入每首歌曲的流派列表,然后它(应该)将每首歌曲的流派拉入列表中,并按最常见的前三个对它们进行排序。

流派以这种方式放入单个文本字段中:

(基本时尚,不是实际结果):

blues rock, garage rock, hard rock

这是我的代码:

$sql = "SELECT `song_name`, `song_genres` FROM `songs` WHERE `album_id` = '$songAlbumId'";
$query = mysqli_query($conn, $sql);

while ($row = mysqli_fetch_array($query)){

$song_name = $row['song_name'];
$song_genres = explode(", ", $row['song_genres']);

for ($i = 0; $i < count($song_genres); $i++){
$count=array_count_values($song_genres);//Counts the values in the array, returns associatve array
arsort($count);//Sort it from highest to lowest
$keys=array_keys($count);//Split the array so we can find the most occuring key
echo $keys[$i] . "<br>";

}
}

这最终给了我:

Hard Rock
Garage Rock
Hard Rock
Garage Rock
Psychedelic Rock
Blues Rock
Garage Rock
Hard Rock

另请注意,专辑 ID 或其他任何内容都没有问题。它专门与正确排序的流派有关。

最佳答案

规范类型。使用 genres 表而不是逗号分隔的列表,并使用附加的 songs_genres 表将歌曲链接到流派。然后就可以从数据库获取数据了,不需要再php中的逻辑了

SELECT g.name, COUNT(DISTINCT(sg.song_id)) cnt
FROM genres g
INNER JOIN songs_genres sg ON sg.genre_id = g.id
GROUP BY g.name
ORDER BY cnt DESC
LIMIT 3

关于php - 在php中从数据库中提取前三项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28249712/

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