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!

Jonathan Clark
  • 19,726
  • 29
  • 111
  • 175

2 Answers2

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');
AlienWebguy
  • 76,997
  • 17
  • 122
  • 145
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']);
}
AlienWebguy
  • 76,997
  • 17
  • 122
  • 145
PeeHaa
  • 71,436
  • 58
  • 190
  • 262
  • 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? – Jonathan Clark Aug 20 '11 at 17:01
  • 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'. – Jonathan Clark Aug 20 '11 at 17:06
  • Still having problems I´m afraid. – Jonathan Clark Aug 26 '11 at 16:16
  • @Jonathan Clark: perhaps it's best if we go to chat to see what the problem is – PeeHaa Aug 26 '11 at 16:17
  • why not just `usort ($your_array['contacts'], 'sort_by_lastname');` ?? – RiaD Aug 26 '11 at 18:40
  • Removed my upvote as Matt is correct. If it gets fixed, I'll put it back. – AlienWebguy Aug 26 '11 at 20:25
  • @Matt: can you try? Seems it works as I assume.function sort_by_lastname($a, $b) { return strcmp($a['user']['basic']['lastname'], $b['user']['basic']['lastname']); } $x=array('c'=> array( array('user'=> array('basic'=> array('lastname'=>'y') ) ), array('user'=> array('basic'=> array('lastname'=>'x') ) ) )); usort($x['c'],'sort_by_lastname'); var_dump($x); – RiaD Aug 27 '11 at 08:12
  • It can't work. `$a['user']['basic']` is a JSON array. No associative keys. Look at @AlienWebguy's solution how he references the `['lastname']` index. – Maverick Aug 27 '11 at 20:19