How to sort a multi dimensional array in PHP alphabetically?

后端 未结 2 1965
误落风尘
误落风尘 2021-01-26 07:36

My API written in PHP (Codeigniter) outputs users based on a selected keyword how can I sort this array in alphabetical order before it outputs to JSON.

This is the outp

相关标签:
2条回答
  • 2021-01-26 08:28

    This one works. Tried, tested, and true:

    function sort_by_lastname($a, $b) {
        $a = trim($a['user']['basic'][0]['lastname']);
        $b = trim($b['user']['basic'][0]['lastname']);
        return strcmp($a,$b);
    }
    
    uasort($array['contacts'],'sort_by_lastname');
    
    0 讨论(0)
  • 2021-01-26 08:31

    You can use usort for this: http://php.net/manual/en/function.usort.php

    Which enables you to sort using your own function.

    Example:

    $users = $your_array['contacts'];
    // or $users = $your_array->contacts;
    
    usort ($users, 'sort_by_lastname');
    
    $your_array['contacts'] = $users;
    // or $your_array->contacts = $users; if it's json instead of array
    
    function sort_by_lastname($a, $b)
    {
        return strcmp($a['user']['basic']['lastname'], $b['user']['basic']['lastname']);
    }
    
    0 讨论(0)
提交回复
热议问题