简体   繁体   中英

PHP pull data from array based on time

I have an array:

array(2) {
  ["Status"]=>
  string(3) "001"
  ["Data"]=>
  array(1) {
    ["item"]=>
    array(87) {
      [0]=>
      array(36) {
        ["StartDate"]=>
        string(10) "2017-01-13"
        ["StartTime"]=>
        string(8) "07:02:18"
      }
    }
  }
}

I'd like to basically selected data from it ONLY if the StartTime is in the last 30 seconds - according to server time.

What is the best way to do this?

You can use array_filter() function:

$out = array_filter(
    $values, // your original array
    function($element)
    {
        $current_time = time();

        // change the keys to match your input 
        $element_time = strtotime($element['start_date'] . 
                                  ' ' . 
                                  $element['start_time']);

        // fix this condition according to your needs
        return $current_time - $element_time < 30;
    }
);

// now $out contains filtered values and $values is unchanged
function getFilteredCallsByDate($calls, $since) {
    return new CallbackFilterIterator(new ArrayIterator($calls['Data']['item']), function ($call) use ($since) {
        return strtotime(sprintf('%s %s', $call['StartDate'], $call['StartTime'])) >= strtotime($since);
    });
}

$calls = [
    'Data' => [
        'item' => [
            ['StartDate' => '2017-01-15', 'StartTime' => '07:38:18'],
            ['StartDate' => '2017-01-15', 'StartTime' => '08:38:18'],
            ['StartDate' => '2017-01-15', 'StartTime' => '11:25:59'],
        ]
    ]
];

var_dump($calls);

echo "The time is " . date("h:i:sa");

foreach (getFilteredCallsByDate($calls, '-30 seconds') as $call) {
    var_dump($call);
}

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