简体   繁体   中英

how to create an array using days key in php

I have an array of object with dynamic date and days. I want to sort array with days keys in php in the order of the days.

Given input like this:
array(

[17-08-2017] => stdClass Object
    (
        [days] => Thu
    ) 

[21-08-2017] => stdClass Object
    (
        [days] => Mon
    )

[22-08-2017] => stdClass Object
    (
        [days] => Tue
    )

[23-08-2017] => stdClass Object
    (
        [days] => Wed
    )
);

I want result like this:

array(

[21-08-2017] => stdClass Object
    (
        [days] => Mon
    )
[22-08-2017] => stdClass Object
    (
        [days] => Tue
    )

[23-08-2017] => stdClass Object
    (
        [days] => Wed
    )

[17-08-2017] => stdClass Object
    (
        [days] => Thu
    )

);

I know this is the stupid idea but how can I do this. Please help me.

convert your key to strtotime($key)

then apply ksort($dates) but it will eliminate the duplicate key.

Probably the same question

You need a custom sorting function.

$t = new DateTime('this week'); //Using this to hopefully adapt for locale wrt which day is first

$daysOrder = [];
for ($i=0;$i<7;$i++) {
    $daysOrder [] = $t->format("D");
    $t->add(new DateInterval("P1D"));
}
$daysOrder = array_flip($daysOrder); //Days as keys, order as values

Then you can sort:

 $array = uasort($array, function ($x,$y) use ($daysOrder) {
        //May need to do some checks here to determine if $x and $y are valid days
        return $daysOrder[$x] <=> $daysOrder[$y]; //PHP 7 syntax
 });

The PHP 5.x syntax would be something like:

 return $daysOrder[$x] < $daysOrder[$y]?-1:($daysOrder[$x]==$daysOrder[$y]?0:1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM