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

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

    You will probably want to create an auxiliar array with the surnames, keep the key, order it and then reconstruct the original array:

    function order_by_surname($names) {
        foreach ($names as $key => $name) {
            $surnames[$key] = array_pop(explode(' ', $name));
        }
        asort($surnames);
        foreach ($surnames as $key => $surname) {
            $ordered[$key] = $names[$key];
        }
        return $ordered;
    

    }

    Also, note that you may have problems with this because the surname is not always the last word of a full name when you have two surnames (e.g. John Clark Moore).

提交回复
热议问题