-5

I have an array which I want to sort on the basis of its specific key before running foreach loop I have tried ksort but It will not work on this sort of situation

[0]=>
  object(stdClass)#4829 (23) {
    ["ID"]=>
    string(4) "4089"
    ["post_author"]=>
    string(1) "1"
    ["post_date"]=>
    string(19) "2018-10-31 06:28:57"
    ["post_date_gmt"]=>
    string(19) "2018-10-31 06:28:57"
    ["post_content"]=>
    string(48) "Sessions move 1 hour earlier from 30th September"
    ["post_title"]=> 'test'
}
[1]=>
  object(stdClass)#4830 (24) {
    ["ID"]=>
    string(4) "4030"
    ["post_author"]=>
    string(1) "1"
    ["post_date"]=>
    string(19) "2018-10-31 06:28:57"
    ["post_date_gmt"]=>
    string(19) "2018-10-31 06:28:57"
    ["post_content"]=>
    string(48) "Sessions move 1 hour earlier from 30th September"
    ["post_title"]=> 'test'
}

This is the data I am fetching from my database and I want to show this in sorting order with respect to post_date. I need to sort this before running for each loop to show the courses

2 Answers2

0

The best way would be to sort by post_date in your query.

However, if you really wants to do it using PHP you can use array_multisort

And use it like so :

For PHP 5.6+ :

$dates = array_column($yourArray, 'post_date');

array_multisort($dates , SORT_NUMERIC, $yourArray);

In case of a lower version of PHP :

$dates=array();
foreach ($data as $key => $row) {
   $dates[$key]  = $row['post_date'];
}

array_multisort($dates , SORT_NUMERIC, $yourArray);
Dylan KAS
  • 4,840
  • 2
  • 15
  • 33
0

I'm assuming that you use plain MySQL to get the array from the database.

Add ORDER BY post_date to your query.

Marcus
  • 822
  • 1
  • 8
  • 27