PHP从主阵列删除子数组,如果特定的值范围内被发现 [英] PHP Remove subarray from main array if specific value range is found
问题描述
可以说我有以下数组:
[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年5月14日和2014年5月28日之间。然后,(新)阵列将打印以下内容:
What if i want to remove a subarray when the date falls outside a specific range. So if i say wanted to find data where the date is between 2014-05-14 and 2014-05-28. Then the (new) array would print the following:
[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
)
我觉得类似如下:
I thought something like the following:
foreach ($array as $row) {
if($row[5] >= '2014-05-14' && $row[5] <= '2014-05-14') {
// Do Something // e.g. unset subarray?
}
}
或者我应该区别对待它,并通过遍历数组,如果一个子阵符合我的标准创建一个新的数组。其结果是与包含符合我的约会日期范围子数组的数组。我希望这是有道理的,我试图找到最有效的方式来做到这一点。
OR should i approach it differently and iterate through the array and if a subarray matches my criteria create a new array. The result being an array with subarrays that contain dates that meet my date range. I hope this makes sense, i am trying to find the most efficient way to do this.
感谢
推荐答案
有关使用情况下,我会亲自使用 array_filter
:
For the use case described, I would personally use 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;
});
这篇关于PHP从主阵列删除子数组,如果特定的值范围内被发现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!