【问题标题】:PHP get next days of the week depending on current day of the weekPHP 根据星期几获取星期几
【发布时间】:2016-10-22 00:37:27
【问题描述】:

我必须用访客人数填写图表,但是,当显示当前周数据时,我将下一天的值设为 0。

EG:今天是星期一,所以我得到 2016-06-20 作为列值,但下一个列值名称是 0,因为我没有接下来几天的数据。

图表索引必须是这样的:

|| 20 Jun 2016 || 21 Jun 2016 || 22 Jun 2016 || 23 Jun 2016 || etc.

现在我得到了这个:

|| 20 Jun 2016 || 1 Jan 1970 || 1 Jan 1970 || 1 Jan 1970 || etc.

所以我尝试使用此函数填充缺失的日期:

function get_day($count) {
    if ($count == NULL) {
        $dweek = date("w");
        for ($i = 1; $i <= 6; $i++) {
            echo $i;
            switch ($i) {
                case 1:
                    $day = $dweek+1;
                    break;
                case 2:
                    $day = $dweek+2;
                    break;
                case 3:
                    $day = $dweek+3;
                    break;
                case 4:
                    $day = $dweek+4;
                    break;
                case 5:
                    $day = $dweek+5;
                    break;
                case 6:
                    $day = $dweek+6;
                    break;
            }
        }
        $current = date("d M Y",strtotime("+$day day"));
    } else {
        $current = date("d M Y",strtotime($count));
    }
    return $current;
}

但现在我得到了:

|| 20 Jun 2016 || 27 Jun 2016 || 27 Jun 2016 || 27 Jun 2016 || etc.

所以我错过了一些东西,但是 2 小时后我看不到该怎么做。

感谢您的帮助。

【问题讨论】:

  • switch()内部返回是个坏主意,一个函数只能返回一个值一次。
  • 所以为了简化:你有一个开始日期,只需要生成该开始日期之后的六天?
  • 你的逻辑有点不对。请输入您正在调用并使用此功能的代码。我会解决的。
  • @jszobody 完全正确。
  • @andreaem,我不明白你为什么要返回 $day。所以,我需要更多的代码。您可以更新您的问题

标签: php date dayofweek


【解决方案1】:

使用datetime datetime.modify

$res = "|| ";

for ($d = 1; $d < 8; $d++) {
    $dt = new DateTime();
    $m = $dt->modify("+$d days");
    $f = $m->format("d M Y");
    $res .= $f . " || ";
}

echo $res;

【讨论】:

  • 我正在尝试制作这个函数 get_day($count) { if ($count == NULL) { for ($d = 0; $d modify("+$d 天"))->format('d M Y'); s} } else { $current = date("d M Y",strtotime($count)); } 返回$当前; } 但得到了一个意外的对象运算符 (->)
  • 我仍然不明白您的意图,但您的代码中有错字。应该是:function get_day($count = null) { if (empty($count)) { for ($d = 0; $d &lt; 6; $d++) { $current .= ((new DateTime())-&gt;modify("+$d days"))-&gt;format('d M Y'); } } else { $current = date("d M Y",strtotime($count)); } return $current; }
  • 粘贴代码返回相同的错误::语法错误,意外'->' (T_OBJECT_OPERATOR)
  • 使用 PHP 版本
  • 我使用的是 5.5.9-1ubuntu4.17
【解决方案2】:
$date = '2016-06-20'; //replace this by your date
$statement = '';
for($i = 0; $i < 7; $i++){
    $statement.= ' || ' . date('d M y', strtotime("$date +$i day"));
}
echo $statement;

现在,您可以使用您的日期来代替 $date。

DEMO

【讨论】:

  • 谢谢,我必须把这部分代码放在哪里?我必须在 if 语句中添加什么内容?
  • @andreaem,对不起。我有一个错误的理解。我刚刚更新了代码
  • 仍然是 2016 年 6 月 26 日。
  • @andreaem。您可以更改循环中的数字。根据需要自定义它。例如,将 7 更改为 6。
  • 我知道,但我仍然会在 6 月 26 日获得所有结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-07
  • 1970-01-01
相关资源
最近更新 更多