generate array from php while loop

南笙酒味 提交于 2019-12-10 21:39:38

问题


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

$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.


回答1:


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 foreach or while

foreach approach :

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

while approach :

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



回答2:


$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.




回答3:


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[] = $var is 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.



来源:https://stackoverflow.com/questions/9105419/generate-array-from-php-while-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!