Sorting Multidimensional Arrays using PHP

noticed that asort() doesn’t cut the mustard? You need usort()!

take this array of arrays for example:

$people = array();
$person = array(
    'name' => 'Zak',
   'age' => 24,
   'born' => 'Timbuktu'
);
$person2 = array(
    'name' => 'Dave',
   'age' => 30,
   'born' => 'Australia'
);
$person3 = array(
    'name' => 'Fred',
   'age' => 18,
   'born' => 'California'
);
$people[] = $person;
$people[] = $person2;
$people[] = $person3;

Now we can create your own custom sort fields. Here I’ll create an age one. The return values are -1 for less than, 0 for equal, and 1 for greater than (first value versus second):

function sortAge($a,$b)
 {
 if($a["age"]> $b["age"]){return 1;}
 elseif($a["age"] == $b["age"]){return 0;}
 elseif($a["age"]< $b["age"]){return -1;}
 }

And here’s one that sorts alphabetically:

function sortName($a,$b)
 {
     return strcmp($a["name"], $b["name"]);
 }

Finally, to use either of your sorts, we call usort.

usort($people,'sortAge');

Or:

usort($people,'sortAge');

Sorted! 😉

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s