我从数据库中提取一系列类型,我试图按最常见的情况对它们进行排序。但是当我从数据库中提取它们时,它们仍然是分开的:
Array
(
[0] => Blues Rock
[1] => Garage Rock
[2] => Hard Rock
)
Array
(
[0] => Garage Rock
[1] => Blues Rock
[2] => Hard Rock
)
但是我想让它出现在一个可以排序以拉出顶级类型的数组中。它应该看起来像类型:Garage Rock,Blues Rock,Hard Rock
这是我的代码:
$genreSql = "SELECT `genres` FROM `song_genres` WHERE `album_id` = '$album_id' AND `band_id` = '$band_id'";
$queryGenre = mysqli_query($conn, $genreSql) or die (mysqli_error($conn));
while ($rowG = mysqli_fetch_array($queryGenre)){
$genres = $rowG['genres']; // Goes into the db as a string. E.g. "Str1, Str2, Str3"
$genres = explode(", ", $genres);
echo "<pre>";
print_r($genres);
echo "</pre>";
我还没有进一步,因为我只是想把它整理成一个单独的阵列。
可能是因为我不知道自己在做什么 - 因为在数组方面我仍然是垃圾 - 但也许是php的老手会找到一些东西。
答案 0 :(得分:2)
如果更改数据库结构,您将能够进行返回所需值的查询。
但现在你可以做这样的事了
$array_of_array_of_genres[] = [
'Blues Rock',
'Garage Rock',
'Hard Rock',];
$array_of_array_of_genres[] = [
'Garage Rock',
'Blues Rock',
'Hard Rock'];
$array_of_array_of_genres[] = [
'POP',
'Hard Rock'];
$all_genres = call_user_func_array('array_merge', $set_of_set_of_genres);
// {"0":"Blues Rock","1":"Garage Rock","2":"Hard Rock","3":"Garage Rock","4":"Blues Rock","5":"Hard Rock","6":"POP","7":"Hard Rock"}
$count_genres = array_count_values($all_genres);
// {"Blues Rock":2,"Garage Rock":2,"Hard Rock":3,"POP":1}
arsort($count_genres);
// {"Hard Rock":3,"Garage Rock":2,"Blues Rock":2,"POP":1}
$result = array_keys($count_genres);
// {"0":"Hard Rock","1":"Garage Rock","2":"Blues Rock","3":"POP"}
答案 1 :(得分:2)
我会考虑以更好的格式存储您的数据。标准化数据库看起来像:
albums
-id
-name
genres
-id
-name
album_genre
-album_id
-genre_id
album_genre会将一个(专辑)保持为多个(流派)关系:
album_id genre_id
1 2
1 3
1 10
获得总数就像这样简单:
SELECT
b.id AS genre_id, b.name AS genre_name, COUNT(a.genre_id) as total
FROM
album_genre a
JOIN
genres b ON a.genre_id = b.id
GROUP BY
a.genre_id
ORDER BY
total DESC
此模型比存储逗号单独列表更灵活。例如,它还使按流派过滤专辑的过程变得简单而精确。