Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP sort multidimensional array with primary & secondary keys

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?

like image 585
Riccardo Avatar asked Oct 19 '10 12:10

Riccardo


1 Answers

Use usort like this:

$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";

function fct($a ,$b) {

  if ($a['prio'] < $b['prio']) {
    return -1;
  } elseif  ($a['prio'] > $b['prio']) {
    return 1;
  } else {
    return strcmp($b['date'], $a['date']);
  }

}

usort($result, "fct");
print_r($result);

Output:

Array
(
    [0] => Array
        (
            [prio] => 0
            [date] => 2010-05-30
            [post] => May's thoughts
        )

    [1] => Array
        (
            [prio] => 0
            [date] => 2010-04-20
            [post] => April's thoughts
        )

    [2] => Array
        (
            [prio] => 1
            [date] => 2010-02-28
            [post] => February's thoughts
        )

)
like image 106
Toto Avatar answered Oct 12 '22 03:10

Toto