0

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.

Avijit
  • 17
  • 8
  • Well, as I understand, there is not direct way to achieve this.. You need to write custom sorting. Show us what you have tried. – Milan Chheda Aug 23 '17 at 07:36
  • 3
    Possible duplicate of [Sort Multi-dimensional Array by Value](https://stackoverflow.com/questions/2699086/sort-multi-dimensional-array-by-value) – Shaunak Shukla Aug 23 '17 at 07:36
  • Possible duplicate of [php sort array with date as key with date format](https://stackoverflow.com/questions/34613896/php-sort-array-with-date-as-key-with-date-format) – Ahmed Sunny Aug 23 '17 at 07:37
  • check this one also : https://stackoverflow.com/questions/96759/how-do-i-sort-a-multidimensional-array-in-php – Shaunak Shukla Aug 23 '17 at 07:40
  • Detailed tutorial on sorting in PHP : https://stackoverflow.com/questions/17364127/how-can-i-sort-arrays-and-data-in-php – Shaunak Shukla Aug 23 '17 at 07:44

2 Answers2

0

convert your key to strtotime($key)

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

Probably the same question

Ahmed Sunny
  • 2,160
  • 1
  • 21
  • 27
0

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);
apokryfos
  • 38,771
  • 9
  • 70
  • 114