我正在从数据库中提取类型列表,并尝试按最常见的情况对它们进行排序。但是,当我从数据库中提取它们时,它们仍然是分开的:
Array
(
[0] => Blues Rock
[1] => Garage Rock
[2] => Hard Rock
)
Array
(
[0] => Garage Rock
[1] => Blues Rock
[2] => 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的资深人士会找到一些东西。
最佳答案
如果更改数据库结构,则可以进行查询以返回所需值。
但是现在你可以做这样的事情
$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"}