0

I have a function which returns array of objects. This is my function

public function myFunction () {
  $args = [
      'post_type' => 'post',

  ];
  $data = \WordPress\Query::get_posts($args);

  $now = time();
  foreach ($data as $key => $datas) {
    $eventTime = $datas->endtime;
    $eventTimeStr = strtotime($eventTime);
    if ($eventTimeStr < $now) {
      unset($data[$key]);
    }
  }
 return $data;
}

This returns array of objects like so:

Array
(
   [0] => WP_Post Object
    (
        [ID] => 14
        [metadata] => Array
            (
                [post_title] => Event number 3
                [starttime] => 24.11.2019
                [endtime] => 25.11.2019
            )

    )

   [1] => WP_Post Object
    (
        [ID] => 13
        [metadata] => Array
            (
                [post_title] => Event number 1
                [starttime] => 19.1.2017
                [endtime] => 20.1.2017
            )
    )
    [2] => WP_Post Object
    (
        [ID] => 10
        [metadata] => Array
            (
                [post_title] => Event number 2
                [starttime] => 19.1.2018
                [endtime] => 20.1.2018
            )

    )

)

How can I sort the array by property "endtime" so that "Event number 1" is the first one on the list and "Event number 2" second etc. ?

I tried using usort-function inside myFunction() but didn't manage to succeed. Should I create another function outside of myFunction() and access the $data-variable from there? If so, how?

In myFunction() I have formatted the date to Unix Timestamp. I probably should use it?

tereško
  • 58,060
  • 25
  • 98
  • 150
AvoQ
  • 97
  • 1
  • 7

1 Answers1

0

as always, sorting algorithm uses a compare function behind the scene to sort the whole array by comparing two element, for sorting complex stuff like this, one should write compare function and define the logic there for ordering

function compare($a, $b)
{
    return strtotime($a->metadata['endtime']) < strtotime($b->metadata['endtime']);
}

usort($yourarray, 'compare');
shahin mahmud
  • 945
  • 4
  • 11