user1401141
user1401141

Reputation: 21

Sort a 2d array by second level keys formatted as d M Y

$MyArray = [
    [ "13 March 2012" => "Commandes Anticorps et Kits 2012" ],
    [ "4 May 2012" => "Prix de la Chancellerie" ],
    [ "17 April 2012" => "MàJ antivirus Kapersky" ],
    [ "14 May 2012" => "Atelier Formation INSERM" ],
    [ "14 March 2012" => "Webzine AP-HP" ],
    [ "11 April 2011" => "Nouvelle Charte des Publications" ],
    [ "23 April 2012" => "BiblioINSERM: Nouveaux Codes" ],
    [ "7 March 2012" => "Springer : Protocols également en test" ],
    [ "4 October 2011" => "[info.biblioinserm] Archives des titres Springer" ],
];

So I'd like to sort on dates.

Among the various solutions that I have found, I have tried that:

function date_compare($a, $b)
{
    $t1 = strtotime($a['datetime']);
    $t2 = strtotime($b['datetime']);

    return $t1 - $t2;
}

and then called the function:

usort($MyArray, 'date_compare');

but it doesn't work.

Upvotes: 0

Views: 487

Answers (2)

mickmackusa
mickmackusa

Reputation: 47894

Use array_multisort() and array_map() to performantly sort by your dynamic date keys. Demo

array_multisort(
    array_map(fn($row) => date_create_from_format('d M Y', key($row)), $MyArray),
    $MyArray
);
var_export($MyArray);

Upvotes: 0

Michael Berkowski
Michael Berkowski

Reputation: 270617

In your inner arrays, the date strings are actually the array keys. So you need to call strtotime() on the keys themselves. This uses array_keys() to extract the keys from both comparison arrays, and array_shift() to retrieve the first of those (though there's only one).

function date_compare($a, $b)
{
    // Remove the first array key (though there should be only one)
    // from both the $a and $b values:
    $akeys = array_keys($a);
    $akey = array_shift($akeys);
    // Could also use
    // $akey = akeys[0];

    $bkeys = array_keys($b);
    $bkey = array_shift($bkeys);
    // Could also use
    // $bkey = bkeys[0];

    // And call strtotime() on the key date values
    $t1 = strtotime($akey);
    $t2 = strtotime($bkey);

    return $t1 - $t2;
}

usort($MyArray, 'date_compare');

Upvotes: 2

Related Questions