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

前端 未结 6 763
一生所求
一生所求 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:26

    I don't think you could directly do this with PHP's built-in array sorting - although I would be interested if someone corrected me on this.

    The easiest way would be to reverse the names so that it becomes Green, Sarah because then you could use PHPs own sorting functions e.g. using asort() (which maintains the key association).

    If that isn't feasible you will probably need to implement your own custom sorting function. The easiest way of doing that, is to use usort() which allows you to define a custom comparator function. So for example:

    usort($arr, "sortByLastName");
    
    function sortByLastName($a, $b) {
         //DO YOUR COMPARISON IN HERE
    }
    

提交回复
热议问题