月数组从两个输入表单

时间:2014-09-30 17:33:55

标签: php html

编辑:

如何输出

两种形式的月份

$_POST['FromMonth'] = "January";
$_POST['ToMonth'] = "May";

输出结果:

"January, February, March, April, May"

我知道这是针对循环基本的php 但我现在有点困惑。

3 个答案:

答案 0 :(得分:0)

foreach并不像您认为的那样工作。你甚至没有有效的PHP语法。

这是解决您问题的方法。鉴于您已经在$ FM和$ TM中创建了字符串,并且已经创建了$ months数组:

$FMI=array_search($FM,$months);
$TMI=array_search($TM,$months);

$slice=array_slice($months,$FMI,$TMI-$FMI+1); // +1 because you want it to be inclusive

echo implode(", ",$slice);

答案 1 :(得分:0)

这样做可以满足您的需要,但前提是输入的字段与输入字段完全相同。

$output = false;

foreach($months as $month) {
    if ($month == $TF) $output = true;
    if ($output) echo $month;
    if ($month == $TM) break;
}

答案 2 :(得分:0)

首先,我创建一个返回月份数列表的函数。这允许包装,因此输出可以是:11,11,0,1,2,11月,12月,1月,2月,3月。

function get_months_in_period($from, $to)
{
    $months = array();

    if ($to >= $from) {
      $months = range($from, $to); 
    } else {   
      $months = array_merge(range($from, 11), range(0, $to));
    } 

    return $months;
}

其次,我使用以下代码进行显示。

// Get $from and $to from your HTML form.
$from = 8;
$to = 2;

// Hard coded for reference.
$month_names = array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");

// Initialize our variable.
$months_in_period = '';

// Display all the months in the period.
foreach (get_months_in_period($from, $to) as $index) {

    // Just echo.
    echo $month_names[$index] . ' ';

   // Save as a variable.
   $months_in_period .= $month_names[$index] . ' ';
}

// Trim the ending whitespace.
$months_in_period = rtrim($months_in_period);

var_dump($months_in_period);