Site Search
Tweet
Chat LIVE
You are here:
php
»
sort associative (assoc) php array
Sort associative (assoc) PHP array
Written By
PHPin24
Submitted At
2009-07-20 19:07:56
Num Views
732
Category
PHP
Sorting a little more complex array than just the normal PHP array
$clients= new Array();
$clients[0]['id'] = 1;
$clients[0]['name'] = "Dave";
$clients[1]['id'] = 2;
$clients[1]['name'] = "Alex";
$clients[2]['id'] = 3;
$clients[2]['name'] = "Chris";
$clients[3]['id'] = 4;
$clients[3]['name'] = "Cindy";
$clients[4]['id'] = 4;
$clients[4]['name'] = "Albert";
function cmp($a, $b){
return strcmp($a['name'], $b['name']);
}
usort($clients, "cmp");
By PHPin24 @ 2009-07-20 19:07:56
To sort a normal array you can use the
PHP function sort
.
By PHPin24 @ 2009-07-31 22:35:27
To invert the search (descending order) you merely have to invert the two variable in the "cmp" function like this:
function cmp($a, $b){
return strcmp($b['name'], $a['name']);
}
By PHPin24 @ 2009-08-06 09:07:41