我不知道
?我是否能够按照可以理解的方式提出我的问题,但我会尝试。
我有这个php代码,我有兴趣从while循环中"起飞"最后一个变量!!
$c= "2040-01-01 12:00:00";
$d= "2040-01-02 12:00:00";
$date_3 = date("Y-m-d g:i:s", strtotime("$c"));
$date_4 = date("Y-m-d g:i:s", strtotime("$d"));
$results = array($date_1);
$i = $date_3;
while ($i <= $date_4) {
$i = date("Y-m-d g:i:s", strtotime($i));
array_push($results, $i);
$k= $i . "'n";
$chunks = str_split($k, 19);
$nexstring = join(''')', $chunks);
$cane = implode(', (''', str_split($nexstring, 21));
echo $cane; // OUTPUTS -> 2040-01-01 12:00:00'), (' 2040-01-02 12:00:00'), ('
$i = date("Y-m-d g:i:s",strtotime("+1 day", strtotime($i)));
}
echo $cane; // OUTPUTS -> 2040-01-02 12:00:00'), ('
现在我的问题是
为什么$cane while {} 之外回显我一些不同的东西,我应该如何将这个变量存储在 while{} 之外
echo $cane
一次只输出其中一个值。但它在循环内,所以它会运行多次 - 这是你获得所有这些值的唯一原因。当然,如果你再次在循环外回显$cane
,它只会包含你输入的最后一个值 - 以前的值已被输出,但被覆盖。
如果它们应该在循环外部可用,则必须将所有这些值附加到循环中的一个变量中:
$allCane="";
while ($i <= $date_4) {
$i = date("Y-m-d g:i:s", strtotime($i));
array_push($results, $i);
$k= $i . "'n";
$chunks = str_split($k, 19);
$nexstring = join(''')', $chunks);
$cane = implode(', (''', str_split($nexstring, 21));
echo $cane;
$allCane .= $cane; // appends $cane to $allCane
$i = date("Y-m-d g:i:s",strtotime("+1 day", strtotime($i)));
}
echo $allCane;
或者,正如 Dagon(达贡)所指出的,您可以将所有这些值存储在一个数组中:
$allCane = array();
for ( /* ... */ ) {
// ...
$allCane[] = $cane;
// ...
}
/*
$allCane is now
array (
[0] = "2040-01-01 12:00:00'), (' ",
[1] = "2040-01-02 12:00:00'), (' ",
...
)
*/
运行此代码以更好地查看内容:
$results = array($date_1);
$i = $date_3;
$cane = "";
$count = 0;
while ($i <= $date_4)
{
$i = date("Y-m-d g:i:s", strtotime($i));
array_push($results, $i);
$k= $i . "'n";
$chunks = str_split($k, 19);
$nexstring = join(''')', $chunks);
// assign a new value to $cane
$cane = implode(', (''', str_split($nexstring, 21));
echo "Loop $count: $cane <br/>";
$i = date("Y-m-d g:i:s",strtotime("+1 day", strtotime($i)));
$count++;
}
echo "After loop: $cane";