合并多个阵列成一个阵列 [英] Merge multiple arrays into one array

查看:212
本文介绍了合并多个阵列成一个阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从数据库中提取流派的列表,我试图用最常见的出现对它们进行排序。但是,当我拉他们从数据库中,他们仍然分开:

I am pulling a list of genres from a database and I am trying to sort them by the most common occurrences. But when I pull them from the database, they are still separated:

Array
(
    [0] => Blues Rock
    [1] => Garage Rock
    [2] => Hard Rock
)
Array
(
    [0] => Garage Rock
    [1] => Blues Rock
    [2] => Hard Rock
)

但我想它出来到一个数组,可以排序拉顶流派。它应该看起来像流派:车库摇滚,蓝调摇滚,硬摇滚

下面是我的code:

$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>";

我的避风港'得到任何进一步的,因为我只是想给它的所有组织到一个单一的阵列。

I haven' gotten any further because I'm just trying to organize it all into one single array.

这可能是我不知道我在做什么 - 因为我还在废话说到阵列 - 但也许PHP的退伍军人会发现一些

It might be that I don't know what I'm doing - because I'm still crap when it comes to arrays - but maybe veterans of php will find something.

推荐答案

如果您更改数据库结构,你将能够作出查询,返回可取的值。

If you change database structure you will by able to make query that returns desirable values.

但现在你可以做这样的事情。

But now you can do something like this

$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"}            

这篇关于合并多个阵列成一个阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆