如果in_array为空,则使用in_array返回下一个数组

时间:2014-03-10 15:55:48

标签: php arrays

我有一个数组

$array = array(
    array('a', '18:27:15', 'label1'),
    array('b', '18:27:20', 'label2'),
    array('c', '18:27:25', 'label3'),
    array('d', '18:27:30', 'label4'),
    array('e', '18:27:35', 'label5'),
    array('f', '18:27:40', 'label6'),
    array('g', '18:27:45', 'label7'),
    array('h', '18:27:50', 'label8')
);

我正在检查数组中是否有时间字符串,例如,如果我给出

 $end_time="18:27:25";  

我得到了数组结果,但是如果我给出

$end_time="18:27:26";

我得到一个空数组。 但我需要它来返回下一个数组而不是

array('d','18:27:30','label4')

以下是代码

$arr_output = array();
foreach ($array as $key=>$arr1){
    if( in_array($end_time, $arr1) ){
        $arr_output[$key]=$arr1;
    }
}
print_r(arr_output);//Empty

1 个答案:

答案 0 :(得分:0)

您可以将它们转换为时间戳并进行比较:

$result = null;
$target = strtotime('18:27:41');

foreach ($array as $item) {
    $compare = strtotime($item[1]);

    if ($compare >= $target) {
        if (null === $result) {
            $result = $item;
        } else if($target - strtotime($result[1]) < $target - $compare) {
            $result = $item;
        }
    }
}

echo print_r($result, 1);

使用此方法,:20将指向18:27:20:21将指向18:27:25

注意这种方法不需要原始数组按任何特定顺序排列,因为每个项目都要考虑。