繁体   English   中英

PHP根据时间从数组中提取数据

[英]PHP pull data from array based on time

我有一个数组:

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"
      }
    }
  }
}

我只想从StartTime的最后30秒开始基本上从中选择数据-根据服务器时间。

做这个的最好方式是什么?

您可以使用array_filter()函数:

$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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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