解构数组并使用 PHP 重建它

我有一个二维数组


$artists = [

    ["name" => "Post Malone", "song" => "Circles", "genre" => "Pop"],

    ["name" => "Camila Cabello", "song" => "Liar", "genre" => "Pop"],

    ["name" => "Tones and I", "song" => "Dance Monkey", "genre" => "Alternative"],

    ["name" => "Billie Eilish", "song" => "Bad Guy", "genre" => "Alternative"],

];

我正在尝试编写一个按流派组织数组并按流派对不同艺术家进行分组的函数。我的输出应该是这样的:


array (

  'Pop' =>

  array (

    0 => 'Post Malone',

     1 => 'Camila Cabello',

   ),

  'Alternative' =>

   array (

     0 => 'Tones and I',

     1 => 'Billie Eilish',

   ),

)

我试图先构建外部数组


function organizer($artists) {

    $genre = array();

    for ($i = 0; $i < count($artists); $i++) {

        $outterArr = array_push ($artists[$i]["genre"],$genre);

        return $outterArr;

    }



}

但坚持如何在外部数组内构造一个新数组。我对编程和 php 很陌生。请展示我的技能,谢谢!


ABOUTYOU
浏览 137回答 2
2回答

元芳怎么了

您可以使用array_reduce按流派对条目进行分组:$artistsByGenre = array_reduce($artists, static function ($byGenre, $artist) {&nbsp; $byGenre[$artist['genre']][] = $artist['name'];&nbsp; return $byGenre;}, []);演示:https ://3v4l.org/3fU83

白板的微信

function group_by($key, $data) {&nbsp; &nbsp; $result = array();&nbsp; &nbsp; foreach($array as $val) {&nbsp; &nbsp; &nbsp; &nbsp; if(array_key_exists($key, $val)){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $result[$val[$key]][] = $val;&nbsp; &nbsp; &nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $result[""][] = $val;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return $result; }$genres = group_by("genre", $artists);
打开App,查看更多内容
随时随地看视频慕课网APP