如何在PHP中对多维数组中的多维数组进行排序

I'm not able to solve this problem. I tried mostly everything.

I'm doing a home project with a database of song artists and their songs but i stumbled over a big problem which i cannot solve. I read most stackoverflow posts but none helped. I bombarded google with questions about php sorting methods and tried them but without success.

I would really appreciate help. I'm stuck on this for 3 days now...

Here is my problem:

I have my array with my artists ($arr) now how can i sort every song array of each artist by year? The data comes from an .json file.

$arr = array(
    "artists" => array(
        "1" => array(
            "id" => "1",
            "firstname" => "John",
            "lastname" => "Doe",
            "songs" => array(
                array("name" => "song_1", "year" => "1999"),
                array("name" => "song_2", "year" => "1987")
            ),
        ),
        "2" => array(
            "id" => "2",
            "firstname" => "Jane",
            "lastname" => "Doe",
            "songs" => array(
                array("name" => "song_1", "year" => "2000"),
                array("name" => "song_2", "year" => "1999")
            )
        ),
        "3" => array(
            "id" => "3",
            "firstname" => "Mark",
            "lastname" => "Doe",
            "songs" => array(
                array("name" => "song_1", "year" => "1984"),
                array("name" => "song_2", "year" => "1983")
            )
        )
    )
);

I hope, my problem is clear enough. I'm new here and i'm not really friends yet with all the buttons. I just can't wait, to hopefully solve this...

duanke3985
duanke3985 如果它来自数据库,那么你可以按年份ASC进行排序(同时获取歌曲数组)
12 个月之前 回复
duanhui5344
duanhui5344 你到目前为止做了什么?即使它不起作用,也要展示你到目前为止所尝试的内容。
12 个月之前 回复

1个回答

Use array_walk() and usort(). array_walk() is to make an iteration over the array and usort() is to sorting the songs by ASC or DESC order.

array_walk($arr['artists'], function (&$song) {
    usort($song['songs'], function ($a, $b) { return $a['year'] > $b['year'] ? 1 : -1; }); // Ascending order
    //usort($song['songs'], function ($a, $b) { return $a['year'] < $b['year'] ? 1 : -1; }); // Descending order
});

Demo

dou12352
dou12352 这是一个参考电话。 有关详细信息:php.net/manual/en/functions.arguments.php
12 个月之前 回复
douyin4875
douyin4875 您的代码对于找到解决方案非常有帮助,但我真的不明白您实际做了什么......如果您能用非常简短的版本描述您的代码,那将对我未来的编程有所帮助。 例如:&-sing在第一行array_walk上是什么意思($ arr ['artists'],function(&$ song){...
12 个月之前 回复
doujia3441
doujia3441 它似乎现在工作
12 个月之前 回复
duanchongzi9997
duanchongzi9997 工作演示在这里:3v4l.org/M8Vs8
12 个月之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问