简体   繁体   English

如何从日期数组中回显单个日期?

[英]How to echo individual dates from dates array?

Right now my program echo an array of dates generated with for loop . 现在,我的程序回显了使用for loop生成的日期数组。 What I'm trying to do is echo dates individually. 我想做的是分别回显日期。

Initial code 初始码

 // initialize an array with your first date
    $dates = array(strtotime("+11 days", strtotime("2017-09-04")));

    for ($i = 1; $i <= 5; $i++) {// loop 5 times to get the next 5 dates

        // add 7 days to previous date in the array
        $dates[] = strtotime("+7 days", $dates[$i-1]);
    }

    // echo the results
    foreach ($dates as $date) {
        echo date("Y-m-d", $date);
        echo "<br>";
    }

Initial Output 初始输出

2017-09-15
2017-09-22
2017-09-29
2017-10-06
2017-10-13

What I have tried 我尝试过的

echo $dates[0];//print first date
echo "<br>";
echo $dates[1];//print second date

Trial Output 试验输出

1505426400
1506031200

How can I achieve this? 我该如何实现?

Either you need to use date() when outputting the elements as well - as they still are timestamps in the array (you don't change anything in the loop, you just print the elements), or you need to change the elements when you loop over them. 在输出元素时也需要使用date() -因为它们仍然是数组中的时间戳(您无需更改循环中的任何内容,只需打印元素即可),或者需要在输出元素时更改元素遍历他们。

Alternative 1: Format on output 备选方案1:输出格式

Convert from timestamp to datestring on output. 从时间戳转换为输出的日期字符串。 This will still have timestamps in the array. 数组中仍将带有时间戳。

echo date("Y-m-d", $dates[0]);

Alternative 2: Alter the elements in the array 备选方案2:更改数组中的元素

Alternatively, you can alter the value in the array when you loop it through foreach . 另外,当您foreach时可以更改数组中的值。 If you pass by reference , you can change the value of the element inside the loop, by using & (which means that the variable is a reference and not a copy). 如果按引用传递 ,则可以使用&更改循环内元素的值(这意味着变量是引用而不是副本)。 This means that you now have datestrings in the array, and not timestamps. 这意味着您现在在数组中有日期字符串,而不是时间戳。

foreach ($dates as &$date) {
    echo $date = date("Y-m-d", $date);
    echo "<br>";
}

If you pass by reference, you can now print it directly, as it will no longer contain the timestamp, since we changed it to the datestring. 如果通过引用传递,则现在可以直接打印它,因为它将不再包含时间戳记,因为我们已将其更改为日期字符串。

echo $dates[0];

You should only adapt one of the alternatives, whichever is most suitable for your application. 您应该只采用其中一种最适合您的应用程序。

try this 尝试这个

echo date("Y-m-d", ($dates[0])) . '<br>';
echo date("Y-m-d", ($dates[1])) . '<br>';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM