How to sort an array of names by surname preserving the keys

前端 未结 6 765
一生所求
一生所求 2021-01-05 16:59

I have an array as follows:

Array(
    [27] => \'Sarah Green\',
    [29] => \'Adam Brown\',
    [68] => \'Fred Able\'
);

I\'d like

6条回答
  •  北荒
    北荒 (楼主)
    2021-01-05 17:30

    function sortByLastName($a){
        $tmp = $a;
        foreach($tmp as $k => $v){
            $tmp[$k] = substr($v,strrpos($v, ' ')+1);
        }
        asort($tmp);
        $ret = array();
        foreach($tmp as $k => $v){
            $ret[$k] = $a[$k];
        }
        return $ret;
    }
    

    Maybe not the fastest way but it works. It works if they have middle names too.

    This is faster than the accepted answer.

    http://codepad.org/ogGibRpH

提交回复
热议问题