0

ユーザーが3月を選択した場合のように、動的な月をデータベースに挿入したい場合、3月から2月までの12か月のレコードを挿入する必要があります。動的な月を取得していますが、データベースに挿入しようとすると、最初の 12 か月しか挿入されません。ユーザーが [さらに追加] ボタンをクリックすると、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]."')";

}
4

3 に答える 3

0

おそらく、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');
}
于 2013-07-25T11:56:11.413 に答える
0

month 配列には 12 個の値しかないため、その配列の値 23 に移動することはできません。できることは、次のように、配列を 0 から 11 まで 2 回実行することです。

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

またはclydeが示したように、モジュロ演算子を使用できます。これにより、2つのループが無駄にならず、高速になります。

  for($i=0; $i<24 ; $i++)
  {
    echo $insert= "insert into month(month_name) values('".$months[$i % 12]."')";
  }
于 2013-07-25T11:50:34.233 に答える
0

あなたの質問には、データベースにこの一連の月が必要な理由を記載する必要があります。通常は誰もそうしません。通常、人々はトランザクション/イベント レコードのタイムスタンプをデータベースに入れ、それについて報告します。

于 2013-07-25T12:07:45.683 に答える