PHP结果来自两个数组配对日期,其中键是" Y"

时间:2017-12-11 13:32:03

标签: php arrays date arraylist

我有两个数组

$array1 = array("2017-12-08","2017-12-09","2017-12-10","2017-12-11","2017-12-12","2017-12-13","2017-12-14","2017-12-15","2017-12-16","2017-12-17","2017-12-18","2017-12-19","2017-12-20","2017-12-21","2017-12-22");
$array2 = array("Y","Y","Y","Y","Y","N","N","N","Y","Y","Y","N","N","Y","Y");

我需要第一个和最后一个日期,其中键=" Y"。像这样:

$result = array("2017-12-08 - 2017-12-12", "2017-12-16 - 2017-12-18", "2017-12-21 - 2017-12-22");

我怎么能做到这一点? 我尝试过使用array_combine,但之后我不知道如何列出日期配对。

从回答

移出
  

是的,这是一个好主意,Justinas,但结果并不完全是我需要的。你的结果给我的第一个2017-12-08和2017-12-22。但我需要从所有对的第一个和结束日期,如:

"2017-12-08 - 2017-12-12"
"2017-12-16 - 2017-12-18"
"2017-12-21 - 2017-12-22"
  

因为我需要在数据库中插入

INSERT INTO $table start='firstDate' AND end='lastDate'.
  

在这个例子中有3行。

1 个答案:

答案 0 :(得分:0)

首先只查找包含Y值的数组键:

$yes = array_filter($array2, function ($yn) {return $yn == 'Y'});

现在执行$result = array_intersect_key($array1, $yes)以获取array2中Y的日期。

最后获得第一个(current($result))和最后end($result)个日期。

Example