PHP如果找到特定的值范围,则从主数组中删除子数组

时间:2014-07-23 00:57:40

标签: php arrays

假设我有以下数组:

  [9] => Array
    (
        [0] => Bob Smith
        [1] => bobsmith@gmail.com
        [2] => Helsinki
        [3] => 10
        [4] => 34
        [5] => 2014-05-12
    )

[10] => Array
    (
        [0] => John Smith
        [1] => johnsmith@domain.com
        [2] => some values
        [3] => 9
        [4] => 67
        [5] => 2014-05-15
    )

[11] => Array
    (
        [0] => Clarke Kent
        [1] => ckent@superman.com
        [2] => Crystal
        [3] => 9
        [4] => 89 
        [5] => 2014-05-16
    )

如果我想在日期超出特定范围时删除子数组,该怎么办?所以如果我想找到日期在2014-05-14和2014-05-28之间的数据。然后(新)数组将打印以下内容:

 [10] => Array
    (
        [0] => John Smith
        [1] => johnsmith@domain.com
        [2] => some values
        [3] => 9
        [4] => 67
        [5] => 2014-05-15
    )

[11] => Array
    (
        [0] => Clarke Kent
        [1] => ckent@superman.com
        [2] => Crystal
        [3] => 9
        [4] => 89 
        [5] => 2014-05-16
    )

我认为如下:

 foreach ($array as $row) {
     if($row[5] >= '2014-05-14' && $row[5] <= '2014-05-14') {
    // Do Something // e.g. unset subarray?
  }

}

或者我应该以不同的方式处理它并迭代数组,如果子数组匹配我的条件,则创建一个新数组。结果是一个包含子数组的数组,其中包含符合我的日期范围的日期。我希望这是有道理的,我想找到最有效的方法来做到这一点。

由于

1 个答案:

答案 0 :(得分:1)

对于所描述的用例,我个人会使用array_filter

$start_date = DateTime::createFromFormat('Y-m-d', '2014-05-14');
$end_date = DateTime::createFromFormat('Y-m-d', '2014-06-14');

$filtered_array = array_filter($array, function($row) use ($start_date, $end_date) {
                      $date = DateTime::createFromFormat('Y-m-d', $row[5]);
                      return $date >= $start_date && $date <= $end_date;
                  });