0

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 output:

http://pastie.org/2402372

Thankful for all input!

3
  • Why not sorting it directly in your query at Model? Commented Aug 20, 2011 at 18:22
  • I cannot. The array is a combination of different queries. Commented Aug 20, 2011 at 20:31
  • I need to sort by first name. Commented Aug 22, 2011 at 6:10

2 Answers 2

2

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');
Sign up to request clarification or add additional context in comments.

2 Comments

You may use strcmp instead of two-times comparation
@RiaD thanks, forgot that it also returned 0 when equal. Code updated.
1

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

8 Comments

Sounds very interesting! I have looked a bit on it and I cannot construct a function that works with my array. Is it possible that you can show me how to use it?
Can I place the sort_by_lastname function in a helper and then use usort function in the controller? How can I use the code? I get error: Use of undefined constant sort_by_lastname - assumed 'sort_by_lastname'.
Still having problems I´m afraid.
@Jonathan Clark: perhaps it's best if we go to chat to see what the problem is
why not just usort ($your_array['contacts'], 'sort_by_lastname'); ??
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.