合并两个数组并在不匹配的位置插入空白点

时间:2016-12-21 18:39:23

标签: php arrays

我正在构建一个日期请求,我需要构建一个数组但是保持五周一周的格式,所以我可以轻松地将它输出到表格中。

我有这个当前工作日的数组,星期一到星期五,看起来像这样

$weekDays( [0] => 2016-12-19 [1] => 2016-12-20 [2] => 2016-12-21 [3] => 2016-12-22 [4] => 2016-12-23 ) 

和来自用户的数组,其中包含个性化日期

$user( [0] => 2016-12-20 [1] => 2016-12-21 [2] => 2016-12-22)

正如你所看到的,这只是本周五个日期中的三个。我需要合并日期匹配的这两个数组,但保持五天格式,如此

$userThisWeek([0] => NULL [1] => 2016-12-20 [2] => 2016-12-21 [3] => 2016-12-22 [4] => NULL)

我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

试试这个。

// $weekDays( [0] => 2016-12-19 [1] => 2016-12-20 [2] => 2016-12-21 [3] => 2016-12-22 [4] => 2016-12-23 );
   // $user( [0] => 2016-12-20 [1] => 2016-12-21 [2] => 2016-12-22);
    $userThisWeek = array();
    foreach($weekDays as $key=>$value){
       if (array_search($value, $user) === FALSE)
          $userThisWeek[$key] = NULL;
       else
          $userThisWeek[$key] = $value;
    }

答案 1 :(得分:0)

这样的事情:

$userThisWeek = [];

foreach ($weekDays as $key => $day) {
    if (in_array($day, $user) {
        $userThisWeek[$key] = $day;
    } else {
        $userThisWeek[$key] = null;
    }
}