比较数组的第一个值后如何检索数组的第二个值?

时间:2019-05-02 14:18:31

标签: php mysql arrays

如果表中存在给定的时间段,我想检索假期的描述。

所以,我有一个表命名为tbl_holiday。

holiday_id  holiday_date    holiday_desc        
1   4/18/2019   Maundy Thursday 
2   4/19/2019   Good Friday     
3   4/20/2019   Black Friday

我的脚本:

$s = $conn->prepare(SELECT holiday_date, holiday_desc FROM tbl_holiday);
$s->execute();
$res = $s->get_result();
$holiday_res = array();
while ($row=mysqli_fetch_assoc())
{
$holiday_res[] = $row;
}

此外,我还有一段代码可以在一段时间内检索

$from = new DateTime($_GET['from']);
$to = new DateTime($_GET['to']);
$interval = DateInterval::createFromDateString('1 day');
$from->setTime(0, 0);
$to->setTime(0, 0)->add($interval);
$period = new DatePeriod($from, $interval, $to);

foreach ($period as $dt) 
{
 $date = $dt->format("m/d/Y");
}

3 个答案:

答案 0 :(得分:1)

您不需要第二段代码,只需使用mysql查询所需的时段窗口即可。

此示例不安全,请查看mysql注入!

还要确保php文件和数据库中的日期格式匹配

下面我假设$from$to与数据库具有相同的日期格式

 $from = $_GET['from'];
 $to = $_GET['to'];
 $s = $conn->prepare(SELECT holiday_date, holiday_desc FROM tbl_holiday 
 WHERE holiday_date >= '$from' AND holiday_date <= '$to');

答案 1 :(得分:1)

您可以将所有范围推入数组,然后检查数据库holiday_date是否在从and到的范围内,

/**
 * For getting period
 */
$fDate    = $_GET['from'];
$tDate    = $_GET['to'];
$from     = new DateTime($fDate);
$to       = new DateTime($tDate);
$interval = DateInterval::createFromDateString('1 day');
$from->setTime(0, 0);
$to->setTime(0, 0)->add($interval);
$period = new DatePeriod($from, $interval, $to);
$temp = [];
foreach ($period as $dt) {
    $temp[] = $dt->format("m/d/Y");
}
$result = [];
/**
 * Looping through holiday data
 */
foreach ($holiday_res as $key => $value) {
    if(in_array($value['holiday_date'], $temp)){ // checking if holiday comes in range
        $result[] = $value; // if yes then put it in result
    }
}
// $result is what you are looking for

答案 2 :(得分:0)

请考虑重写此行

while ($row=mysqli_fetch_assoc())

while ($row=mysqli_fetch_assoc($res))