如何使用foreach循环将日期数组存储到php中的变量中

时间:2013-12-13 08:07:44

标签: php

<?php
$con = mysql_connect("localhost","root","");
if(!$con)
{
die("cannot connect" . mysql_error());
}
mysql_select_db("test",$con);
$sql = "SELECT Renewal_Date FROM ilist";
$mydata = mysql_query($sql,$con);
$result_array = array();
echo "<table border=2 >
<tr>

   <th>Renewal_Date</th>
</tr>";
  while($record = mysql_fetch_array($mydata)){
  echo"<tr>";

  echo "<td>" . $record['Renewal_Date'] . "</td>";
  echo "</tr>";


}
echo "</table>";
   $date3=array();
   $todayDate = date('m/d/Y');
   $date1 = new DateTime($todayDate);
   $date2 = new DateTime($record['Renewal_Date']);
     foreach($date2 as $date3)
       $interval = $date1->diff($date3);
    echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d."        days ";

mysql_close($con);

?>

我已将更新日期列表提取到数组$记录中,现在我需要存储每个日期 使用foreach的变量,该变量将用于查找与当前日期的差异。     这该怎么做?

regards Sanji   

1 个答案:

答案 0 :(得分:0)

像这样改写...... [你不需要一个foreach构造,而是在同一个while循环中做这个事情]

while($record = mysql_fetch_array($mydata)){
  echo"<tr>";
  echo "<td>" . $record['Renewal_Date'] . "</td>";
  echo "</tr>";
  $todayDate = date('m/d/Y');
  $date1 = new DateTime($todayDate);
  $date2 = new DateTime($record['Renewal_Date']);
  $interval = $date1->diff($date2); //  I assume renewal date should be greater , so it must be $date2->diff($date1);
  echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d."        days ";
}