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
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');
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']);
}