PHP While循环动态会话变量

时间:2017-09-16 22:33:29

标签: php while-loop

使用$_SESSION语句创建动态while变量以从数据库中打印日期。只需要打印日期TuesdayFriday

通过date()strtotime()

获取工作日来实现这一目标
$d = 0;//create dynamic numbers
while($mydate = mysqli_fetch_array($myweekdatesQ)){$d++;

//get weekday of date
$weekday =date('l', strtotime($mydate['event_date']));

if($weekday ==='Tuesday'){
$t = 't_'.$d;
echo $_SESSION[$t] = $mydate['event_date'];
}

if($weekday ==='Friday'){
$f = 'f_'.$d;
echo $_SESSION[$f] = $mydate['event_date'];
}
}

工作得很好,但打印时出现小问题:

$_SESSION[t1];
$_SESSION[f2];
$_SESSION[t3];
$_SESSION[f4];
$_SESSION[t5];
$_SESSION[f6];
$_SESSION[t7];
$_SESSION[f8];

但是,变量$d永远不会小于1且大于4.最终结果应为:

$_SESSION[t1];
$_SESSION[t2];
$_SESSION[t3];
$_SESSION[t4];

$_SESSION[f1];
$_SESSION[f2];
$_SESSION[f3];
$_SESSION[f4];

如何使这项工作?

1 个答案:

答案 0 :(得分:2)

制作两个动态数字:

$d = 0;//create dynamic numbers for $t
$x = 0;//create dynamic numbers for $f
while($mydate = mysqli_fetch_array($myweekdatesQ)) {

    //get weekday of date
    $weekday =date('l', strtotime($mydate['event_date']));

    if($weekday ==='Tuesday') {
        $d++;
        $t = 't_'.$d;
        echo $_SESSION[$t] = $mydate['event_date'];
    }

    if($weekday ==='Friday') {
        $x++;
        $f = 'f_'.$x;
        echo $_SESSION[$f] = $mydate['event_date'];
    }
}