Sort multidimensional array by multiple keys

前端 未结 7 697
挽巷
挽巷 2020-11-22 10:05

I\'m trying to sort a multidimensional array by multiple keys, and I have no idea where to start. I looked at uasort, but wasn\'t quite sure how to write a function for what

7条回答
  •  一整个雨季
    2020-11-22 10:18

    I have tried to below code and i successfully

    array code

    $songs =  array(
            '1' => array('artist'=>'Smashing Pumpkins', 'songname'=>'Soma'),
            '2' => array('artist'=>'The Decemberists', 'songname'=>'The Island'),
            '3' => array('artist'=>'Fleetwood Mac', 'songname' =>'Second-hand News')
    );
    

    call array sorting function

    $songs = subval_sort($songs,'artist'); 
    print_r($songs);
    

    array sorting funcation

    function subval_sort($a,$subkey) {
        foreach($a as $k=>$v) {
            $b[$k] = strtolower($v[$subkey]);
        }
        asort($b);
        foreach($b as $key=>$val) {
            $c[] = $a[$key];
        }
        return $c;
    }
    

    if array reverse sorting function

    function subval_sort($a,$subkey) {
            foreach($a as $k=>$v) {
                $b[$k] = strtolower($v[$subkey]);
            }
            arsort($b);
            foreach($b as $key=>$val) {
                $c[] = $a[$key];
            }
            return $c;
        }
    

提交回复
热议问题