PHP Array sort by string date
Asked Answered
A

1

-1

I have an array that looks like this

array(24) { ["#HiddenId"]=> string(24) "2013-11-08T11:59:54.378Z"] }

It has multiple ids/dates but I want to sort it by date (most recent)

I know how to do this for this format, "01/01/2014" however I Believe it is easier to work with this format, but I'm unsure of how to implement.

This is the code I have for format "01/01/2014"

uasort($fileList, "my_sort");

function my_sort($a,$b)
{
    $date1 = DateTime::createFromFormat('d/m/Y', $a);
    $date2 = DateTime::createFromFormat('d/m/Y', $b);
    return $date1 < $date2;
}

I need to do this function similar but for the other format shown above.

Any help is appreciated

Additament answered 17/4, 2014 at 10:25 Comment(1)
Am I missing something or can this be done with a simple arsort($yourArray) ??Varela
D
2

Very simple:

usort($yourArray,"strcmp");

"Big-endian" formats like Y-m-d H:i:s sort lexicographically.

Dipper answered 17/4, 2014 at 10:28 Comment(7)
How can I reference "hiddenId" without hardcoding like you have?Additament
Isn't that part of your array structure? Don't you know the key of the date?Dipper
@NiettheDarkAbsol Nice answer, but wouldn't rsort work in the same way, while being simpler to use?Labdanum
Well I need to sort the array by dates only, why do I need to reference the key values?Additament
Because... you need to tell it where your date is?Dipper
Ok and if I have 100+ ids with dates, How can i sort all, I need to hard code each id like you have done?Additament
why not just sort($yourArray)?Costin

© 2022 - 2024 — McMap. All rights reserved.