Sorting a Multidimensional Array by Key: A Comprehensive Guide
Arranging the elements of a multidimensional array in a specific order can be a common requirement in programming. Sorting by a particular key provides an efficient way to organize and retrieve data.
Consider the following multidimensional array containing invitations:
Array ( [0] => Array ( [iid] => 1 [invitee] => 174 [nid] => 324343 [showtime] => 2010-05-09 15:15:00 [location] => 13 [status] => 1 [created] => 2010-05-09 15:05:00 [updated] => 2010-05-09 16:24:00 ) [1] => Array ( [iid] => 1 [invitee] => 220 [nid] => 21232 [showtime] => 2010-05-09 15:15:00 [location] => 12 [status] => 0 [created] => 2010-05-10 18:11:00 [updated] => 2010-05-10 18:11:00 ))
To sort this array by the "status" key, we can employ the usort() function and a custom comparison function.
Custom Comparison Function
The comparison function determines the order of the elements by comparing their keys. Here's a function that compares based on the "status" key:
function cmp($a, $b) { if ($a['status'] == $b['status']) { return 0; } return ($a['status'] < $b['status']) ? -1 : 1; }
This function returns -1 when $a should come before $b, 1 when $a should come after $b, and 0 when they are equal.
Sorting the Array
We can now sort the array using usort():
usort($array, "cmp");
This will sort the array by the "status" key in ascending order. If we want to reverse the order, we can use rsort():
rsort($array, "cmp");
By utilizing the provided comparison function and sorting functions, we can effortlessly sort multidimensional arrays by any desired key.
The above is the detailed content of How to Sort a Multidimensional Array by Key: A Step-by-Step Solution?. For more information, please follow other related articles on the PHP Chinese website!