php 从php while循环生成数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9105419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 06:10:44  来源:igfitidea点击:

generate array from php while loop

phparraysloopswhile-loop

提问by grantiago

I want to run a while(or any) loop to output a small list of dates as an array

我想运行一个while(或任何)循环来输出一个小的日期列表作为数组

$start = $day = strtotime("-1 day");
$end = strtotime('+6 day');
while($day < $end)
{
    echo  date('d-M-Y', $day) .'<br />';
    $day = strtotime("+1 day", $day) ;
}

This works fine for printing, but I want to save it as an array (and insert it in a mysql db). Yes! I don't know what I'm doing.

这适用于打印,但我想将其保存为数组(并将其插入到 mysql 数据库中)。是的!我不知道我在做什么。

回答by Bogdan

to create a array, you need to first initialize it outside your loop (because of variable scoping)

要创建一个数组,您需要先在循环外初始化它(因为变量范围)

$start = $day = strtotime("-1 day");
$end = strtotime('+6 day');
$dates = array(); //added
while($day < $end)
{
    $dates[] = date('d-M-Y', $day); // modified
    $day = strtotime("+1 day", $day) ;
}
echo "<pre>";
var_dump($dates);
echo "</pre>";

you can then use your dates using either foreachor while

然后您可以使用您的日期使用foreachwhile

foreach approach :

foreach 方法:

foreach($dates as $date){
     echo $date."<br>";
}

while approach :

而方法:

$max =  count($dates);
$i = 0;
while($i < $max){
    echo $dates[$i]."<br>";
}

回答by Niet the Dark Absol

$arr = Array();
while(...) {
   $arr[] = "next element";
   ...
}

The []adds a new element to an array, just like push()but without the overhead of calling a function.

[]一个阵列增加了一个新的元素,就像push()但是没有调用函数的开销。

回答by Aatch

The simple way is just:

简单的方法就是:

$start = $day = strtotime("-1 day");
$end = strtotime('+6 day');
$arr = array();
while($day < $end)
{
    $arr[] = date('d-M-Y', $day);
    $day = strtotime("+1 day", $day) ;
}

// Do stuff with $arr

the $arr[] = $varis the syntax for appending to an array in PHP. Arrays in php do not have a fixed size and therefore can be appended to easily.

$arr[] = $var是在 PHP 中追加到数组的语法。php 中的数组没有固定的大小,因此可以很容易地附加到。