0

我不知道我是否能够以可能被理解的方式提出我的问题,但我会尝试。

我有这个 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{} 之外是相同的?

4

2 回答 2

2

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'), (' ",
      ...
   )
*/
于 2013-11-13T21:03:21.163 回答
0

运行此代码以更好地查看内容:

$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";  
于 2013-11-13T21:10:17.180 回答