编辑:
如何输出
两种形式的月份
$_POST['FromMonth'] = "January";
$_POST['ToMonth'] = "May";
输出结果:
"January, February, March, April, May"
我知道这是用于循环的基本php但我现在有点困惑。
首先,我创建一个函数,返回月份编号的列表。这允许包装,因此11月、12月、1月、2月和3月的输出可以是:10、11、0、1、2。
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);
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);
这将执行您想要的操作,但前提是在输入字段中输入的名称与数组中的名称完全相同。
$output = false;
foreach($months as $month) {
if ($month == $TF) $output = true;
if ($output) echo $month;
if ($month == $TM) break;
}