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

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

    You can use the uasort function, which allows you to specify a custom sorting method while also preserving keys:

     'Sarah Green',
        29 => 'Adam Brown',
        68 => 'Fred Able'
    );
    
    // Perform the sort:
    uasort($array, 'lastNameSort');
    
    // Print the result:
    print_r($array);
    ?>
    

    Here's a demo.

提交回复
热议问题