A multidimensional array of PHP sorts with primary and secondary keys

How do you sort a multidimensional array using primary and secondary keys? For example, assuming the following array:

$result = array();

$result[0]["prio"] = 1;
$result[0]["date"] = '2010-02-28';
$result[0]["post"] = "February thoughts";

$result[1]["prio"] = 0;
$result[1]["date"] = '2010-04-20';
$result[1]["post"] = "April thoughts";

$result[2]["prio"] = 0;
$result[2]["date"] = '2010-05-30';
$result[2]["post"] = "May thoughts";

I want to sort the column "prio" as the primary key (ascending) and "date" as the secondary key (descending) to get:

$result[0]["prio"] = 0;
$result[0]["date"] = '2010-05-30';
$result[0]["post"] = "May thoughts";
$result[1]["prio"] = 0;
$result[1]["date"] = '2010-04-20';
$result[1]["post"] = "April thoughts";
$result[2]["prio"] = 1;
$result[2]["date"] = '2010-02-28';
$result[2]["post"] = "February thoughts";

How to do it?

+3
source share
4 answers

Use usort as follows:

$result = array();

$result[0]["prio"] = 1;
$result[0]["date"] = '2010-02-28';
$result[0]["post"] = "February thoughts";

$result[1]["prio"] = 0;
$result[1]["date"] = '2010-04-20';
$result[1]["post"] = "April thoughts";

$result[2]["prio"] = 0;
$result[2]["date"] = '2010-05-30';
$result[2]["post"] = "May 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);

Conclusion:

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

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

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

)
+5
source

array_multisort() ... β„– 3 PHP , datestamp .

, sql, .

+2

PHP , usort(), , , .

, PHP, , .

+1

usort() .

<?php
function cmp($a, $b)
{
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

$a = array(3, 2, 5, 6, 1);

usort($a, "cmp");

foreach ($a as $key => $value) {
    echo "$key: $value\n";
}
?>

0: 1
1: 2
2: 3
3: 5
4: 6

Further information can be found at http://www.php.net/manual/en/function.usort.php.
This should help you get started.

0
source

Source: https://habr.com/ru/post/1770305/


All Articles