-1

I have this array:

$user_data = array();
while($row=mysql_fetch_array($result))
{
$user_data[$row['id_user']]['id_user'] = $row['id_user'];
$user_data[$row['id_user']]['firstname'] = $row['firstname'];
$user_data[$row['id_user']]['lastname'] = $row['lastname'];
$user_data[$row['id_user']]['avatar'] = $row['avatar'];
}

I'd like to sort it using php (not sql or Jquery) by firstname for example.

leppie
  • 115,091
  • 17
  • 196
  • 297
echo
  • 89
  • 2
  • 10

5 Answers5

0

Look at the doc.

You should use the SORT_STRING flags to sort by firstname.

Val
  • 762
  • 8
  • 32
0

What you will probably want to use is php's uasort function. It allows you to specify your own comparison function that will be used in the sorting process.

PHP documentation: uasort

MrHug
  • 1,315
  • 10
  • 27
0

Sort it by firstname in your database query:

...
ORDER BY firstname

After all, it is database that retrieves the data. No point doing the work again of dealing with data when you could have done that in the first step.

Andrius Naruševičius
  • 8,348
  • 7
  • 49
  • 78
0

The manual for array_multisort has an example exactly for this use case:

$data[] = array('volume' => 67, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 1);
$data[] = array('volume' => 85, 'edition' => 6);
$data[] = array('volume' => 98, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 6);
$data[] = array('volume' => 67, 'edition' => 7);

// Obtain a list of columns
foreach ($data as $key => $row) {
    $volume[$key]  = $row['volume'];
    $edition[$key] = $row['edition'];
}

// Sort the data with volume descending, edition ascending
// Add $data as the last parameter, to sort by the common key
array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);
Fabian Schmengler
  • 24,155
  • 9
  • 79
  • 111
  • The same as [this answer](http://stackoverflow.com/a/4582659/1384214). – Val Feb 21 '13 at 11:03
  • It seems like it should work, however it does not. Don't know what I'm doing wrong. Could you take a look at my code at OP and tell me how exactly should I write the sort code? – echo Feb 21 '13 at 12:28
  • Never mind, I got it. – echo Feb 21 '13 at 12:50
0

Add this after while loop and try :

$sort = array();
foreach($user_data as $k=>$v) {
    $sort['firstname'][$k] = $v['firstname'];
}

array_multisort($sort['firstname'], SORT_DESC, $user_data);


echo "<pre>";
print_r($user_data);

Not tested, If you are getting any issue, please comment here.

Prasanth Bendra
  • 31,145
  • 9
  • 53
  • 73