Php 如何在循环中重复几个月?

Php 如何在循环中重复几个月?,php,mysql,loops,Php,Mysql,Loops,我想在数据库中插入动态月份,就像用户选择三月一样,然后我需要插入从三月到二月的12个月的记录。我得到了动态的月份,但当我试图将其插入数据库时,它只插入前12个月。如果用户单击AddMore按钮,我需要从3月到2月再次重复循环。这是我的代码: $months = array(); $date="august"; $year= '2014'; //$y= (int)$year; $currentMonth= date('m', strtotime($date)); $currentyear= dat

我想在数据库中插入动态月份,就像用户选择三月一样,然后我需要插入从三月到二月的12个月的记录。我得到了动态的月份,但当我试图将其插入数据库时,它只插入前12个月。如果用户单击AddMore按钮,我需要从3月到2月再次重复循环。这是我的代码:

$months = array();
$date="august";
$year= '2014';
//$y= (int)$year;
$currentMonth= date('m', strtotime($date));
$currentyear= date('Y', strtotime('+1 year'));
for($x = $currentMonth; $x < $currentMonth+12; $x++) 
{ 
    $months[] = date('F Y', mktime(0, 0, $currentyear, $x,1));
}
//print_r($months);
for($i=0; $i<=23 ; $i++)
{

 echo $insert= "insert into month(month_name) values('".$months[$i]."')";

}
$months=array();
$date=“八月”;
$year='2014';
//$y=(int)$year;
$currentMonth=日期('m',标准时间($date));
$currentyear=日期('Y',标准时间('1年');
对于($x=$currentMonth;$x<$currentMonth+12;$x++)
{ 
$months[]=日期('fy',mktime(0,0,$currentyear,$x,1));
}
//印刷费(月);

对于($i=0;$i),由于months数组只有12个值,因此无法转到该数组中的值23。您可以做的是从0到11在数组中运行两次,如下所示:

for($j=0; $j<2 ; $j++)
{
  for($i=0; $i<12 ; $i++)
  {
    echo $insert= "insert into month(month_name) values('".$months[$i]."')";
  }
}

for($j=0;$j也许您可以使用DateTime对象来执行此操作

$string = '01-08-2013'; //input string from user

$StartDate = new DateTime($string); 
$StopDate = new DateTime($string);
$StopDate->modify('+1 year');

while($StartDate < $StopDate) { //loop as long as $StartDate is smaller than $StopDate
    echo "inserting " . $StartDate->format('d/m/Y') . ' into database ' . "<br/>";

    //execute mysql query;

    $StartDate->modify('+1 month');
}
$string='01-08-2013';//从用户输入字符串
$StartDate=新日期时间($string);
$StopDate=新日期时间($string);
$StopDate->修改(“+1年”);
而($StartDate<$StopDate){//只要$StartDate小于$StopDate,就循环
将“$StartDate->format('d/m/Y')”插入数据库“
”; //执行mysql查询; $StartDate->修改(“+1个月”); }
您的问题应该说明为什么要在数据库中保存这一系列的月份,因为通常没有人这样做。通常人们会将事务/事件记录的时间戳放入数据库,然后对其进行报告。

您在可能是一个循环的事情上浪费了两个循环,使用模运算符,或者我如何找到2在$j循环中。由于您的演示没有指示动态值,我似乎不知道您的动态值应该来自何处。在您的演示中,您也只是在其中硬编码“23”。那么该如何定义此变量?这是您所说的“添加按钮”吗?我在尝试添加另一个具有月份的字段时遇到此错误。例如($i=0;$i<24;$i++){echo$insert=“插入月份(月份名称,销售)值(“$months[$i%12]”,“,“$sale[$i]”)。”)“
;”你能用这个额外的问题和一些关于错误的解释来编辑这个问题吗?因为我从这里看不到任何东西。事实上,听起来你的数据库模型很奇怪。你为什么要以某种顺序插入所有12个月呢?而且,月数组的长度不会超过12,所以使用u直到23将导致错误。
$string = '01-08-2013'; //input string from user

$StartDate = new DateTime($string); 
$StopDate = new DateTime($string);
$StopDate->modify('+1 year');

while($StartDate < $StopDate) { //loop as long as $StartDate is smaller than $StopDate
    echo "inserting " . $StartDate->format('d/m/Y') . ' into database ' . "<br/>";

    //execute mysql query;

    $StartDate->modify('+1 month');
}