How do you sort a multidimensional array by primary and secondary key? For example, assuming the following array:
$result = array();
$result[0]["prio"] = 1;
$result[0]["date"] = '2010-02-28';
$result[0]["post"] = "February's thoughts";
$result[1]["prio"] = 0;
$result[1]["date"] = '2010-04-20';
$result[1]["post"] = "April's thoughts";
$result[2]["prio"] = 0;
$result[2]["date"] = '2010-05-30';
$result[2]["post"] = "May's thoughts";
I wish to sort the column 'prio' as the primary key (ascending) and 'date' as the secondary key (descending), to obtain:
$result[0]["prio"] = 0;
$result[0]["date"] = '2010-05-30';
$result[0]["post"] = "May's thoughts";
$result[1]["prio"] = 0;
$result[1]["date"] = '2010-04-20';
$result[1]["post"] = "April's thoughts";
$result[2]["prio"] = 1;
$result[2]["date"] = '2010-02-28';
$result[2]["post"] = "February's thoughts";
How to achieve this?
PHP doesn't have a built-in function to do complex sorting like this, so you'll need to do a
usort()
, which allows you to sort items using a function that specifies your own criteria.The example given on the PHP manual page is almost an exact match for what you want to achieve.
array_multisort() should give you the functionality that you need... use Example #3 from the PHP documentation as the basis for your sort, although you'll need to convert those date strings to a datestamp value before executing the sort.
If this data has come from a database query though, it's far easier to sort it within the sql query used to retrieve the information.
Use usort like this:
Output:
You may use
usort()
to define custom sort function.Here's an example
The output will be
More info can be found at http://www.php.net/manual/en/function.usort.php
It should help you get started.