下面代码的作用是检索完整选项类型中的各个选项。因此,例如,如果$ option是A-D,那么通过使用explode,它将能够显示每个单独的选项以输出A B C D.
现在在这个例子中我希望A B C D每个都拥有它自己的复选框。但是使用下面的代码,它只是创建A和D的复选框,它应该是A
,B
,C
,D
的第一个和最后一个选项。怎么办呢?
function ExpandOptionType($option) {
$options = explode('-', $option);
foreach($options as $indivOption) {
echo '<p><input type="checkbox" name="options[]" id="option-' . $indivOption . '" value="' . $indivOption . '" /><label for="option-' . $indivOption . '">' . $indivOption . '</label></p>';
}
if(count($options) > 1) {
$start = array_shift($options);
$end = array_shift($options);
do {
$options[] = $start;
}while(++$start <= $end);
}
else{
$options = explode(' or ', $option);
}
return implode(" ", $options);
}
答案 0 :(得分:1)
好吧,我不太清楚你的函数中的if-else
是做什么的,但这是你在想什么?
<?php foreach (range('A','D') as $letter): ?>
<p>
<input type="checkbox" name="options[]" id="option-<?php echo $letter ?>" value="<?php echo $letter ?>" />
<label for="option-<?php echo $letter ?>"><?php echo $letter ?></label>
</p>
<?php endforeach ?>
或者,在函数中:
function ExpandOptionType($from, $to) {
$output = '';
$range = range($from, $to);
foreach ($range as $letter) {
$output .= '<p>';
$output .= "<input type=\"checkbox\" name=\"options[]\" id=\"option-{$letter}\" value=\"{$letter}\" />";
$output .= "<label for=\"option-{$letter}\">{$letter}</label>";
$output .= '</p>';
}
return $output;
}
echo ExpandOptionType('A', 'D');
答案 1 :(得分:1)
function ExpandOptionType($option) {
$options = explode('-', $option);
if(count($options) > 1) {
$start = array_shift($options);
$end = array_shift($options);
do {
$options[] = $start;
}while(++$start <= $end);
}
else{
$options = explode(' or ', $option);
}
foreach($options as $indivOption) {
echo '<p><input type="checkbox" name="options[]" id="option-' . $indivOption . '" value="' . $indivOption . '" /><label for="option-' . $indivOption . '">' . $indivOption . '</label></p>';
}
return implode(" ", $options);
}
这样您首先更改选项数组,然后创建复选框。