基于PHP上数据库上的数组数据,无法匹配日期日期

时间:2018-11-14 06:33:26

标签: php arrays codeigniter-3

我有一个月的请假日期数据,其中有各种日期,我试图按本月的日期来匹配数据。当我基于行数据进行设置时,只会显示一个日期。如果它是一个数组,我不太了解逻辑。

我的桌子

   | ID  |   id   |  start_date  |   end_date   | 
   | ____|________|______________|______________|
   |  1  |   x1   |  2018-11-05  |  2018-11-05  |
   |  1  |   x1   |  2018-11-12  |  2018-11-15  |
   |  3  |   x1   |  2018-11-19  |  2018-11-21  |

我的脚本

    $timesheet = $this->db->select('*')
                      ->where('MONTH(start_date)', 11)
                      ->where('YEAR(start_date)', 2018)
                      ->where('id', 'x1')
                      ->get();
    $result = $timesheet->row_array();                    
    $day_start=date_create($result['start_date']);
    $day_end=date_create($result['end_date']);      

    for ($x = 1; $x <= 30; $x++) {
        if($x >=$day_start->format('d') and $x <= $day_end->format('d')){
           echo "<td class='bg-warning'>Y</td>";
        }else{
            echo "<td>N</td>";
        }
    }   

    /** MY result data **/

    | Date  | ... | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | ... | 
    ----------------------------------------------------------------
    | Result| ... | N |  N |  N |  Y | Y  | N  | N  |  N |  N | ... |


    /** the results I expected **/
    | Date  | ... | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | ... | 
    ----------------------------------------------------------------
    | Result| ... | N |  Y |  N |  Y | Y  | N  | Y  |  Y |  Y | ... |

1 个答案:

答案 0 :(得分:0)

如果您想将所有记录合并在一起,则需要构建一个日期数组(我使用array_fill()创建日期并将每个记录设置为“ N”开始)。

然后您遍历每个结果行,并将Y添加到适当的元素中。然后,您可以使用for()循环从开始到结束的那一天进行循环,以'Y'填充各天。

最后,您可以输出包含所有各行的$dates数组。

$dates = array_fill(1, 30, "N");
foreach ($timesheet->result_array() as $result) {
    $start = (int)$result['start_date']->format('d');
    $end = (int)$result['end_date']->format('d');
    for ( $i = $start; $i <= $end; $i++ )   {
        $dates[$i] = "Y";
    }
}

foreach ( $dates as $day )  {
    if($day == "Y") {
        echo "<td class='bg-warning'>Y</td>";
    }else{
        echo "<td>N</td>";
    }
}

您可能希望将array_fill()更改为与您工作的月份相对应的天数,但这可以在需要时进行分类。