我正在尝试通过检查mysqli变量来编译if语句以检查回复类型是Single
还是Multiple
。如果Single
然后输出选项作为单选按钮,如果Multiple
则输出选项作为复选框。
但我在$qandaReplyType
的if语句中收到一个未定义的变量错误。如何解决这个问题?
以下代码:
$qandaquery = "SELECT q.QuestionId, r.ReplyType
FROM Question q
LEFT JOIN Reply r ON q.ReplyId = r.ReplyId
WHERE SessionId = ?
GROUP BY q.QuestionId
ORDER BY RAND()";
$qandaqrystmt=$mysqli->prepare($qandaquery);
// get result and assign variables (prefix with db)
$qandaqrystmt->execute();
$qandaqrystmt->bind_result($qandaQuestionId,$qandaReplyType);
$arrReplyType = array();
while ($qandaqrystmt->fetch()) {
$arrReplyType[ $qandaQuestionId ] = $qandaReplyType;
}
$qandaqrystmt->close();
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);
}
if($qandaReplyType == 'Single'){
foreach($options as $indivOption) {
echo '<div class="ck-button"><label class="fixedLabelCheckbox"><input type="radio" name="options_<?php echo $key; ?>[]" id="option-' . $indivOption . '" value="' . $indivOption . '" /><span>' . $indivOption . '</span></label></div>';
}
}else if($qandaReplyType == 'Multiple'){
foreach($options as $indivOption) {
echo '<div class="ck-button"><label class="fixedLabelCheckbox"><input type="checkbox" name="options_<?php echo $key; ?>[]" id="option-' . $indivOption . '" value="' . $indivOption . '" /><span>' . $indivOption . '</span></label></div>';
}
}
}
foreach ($arrQuestionId as $key=>$question) {
echo ExpandOptionType(htmlspecialchars($arrOptionType[$key]));
}
?>
答案 0 :(得分:3)
$qandaReplyType
。
在使用变量的全局版本之前,您需要在函数中包含global $qandaReplyType
。
在PHP中使用variable scope时不会受到伤害。
修改:根据它的外观,$arrQuestionId
和$arrOptionType
也不在功能范围内。
global $qandaReplyType, $arrQuestionId, $arrOptionType;
答案 1 :(得分:0)
Mmmmmmm .....你的功能......试试这个:
function ExpandOptionType($option) {
$qandaReplyType = "Single";
$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);
}
if($qandaReplyType == 'Single'){
foreach($options as $indivOption) {
echo '<div class="ck-button"><label class="fixedLabelCheckbox"><input type="radio"
name="options_<?php echo $key; ?>[]" id="option-' . $indivOption . '" value="' .
$indivOption . '" /><span>' . $indivOption . '</span></label></div>';
}
}else if($qandaReplyType == 'Multiple'){
foreach($options as $indivOption) {
echo '<div class="ck-button"><label class="fixedLabelCheckbox"><input type="checkbox" name="options_<?php echo $key; ?>[]" id="option-' . $indivOption . '" value="' . $indivOption . '" /><span>' . $indivOption . '</span></label></div>';
}
}
}
如果这样可行,那么$ qandaReplyType没有在函数内部定义....你应该找到一种方法来恢复该值o可能会在函数中添加另一个参数并传递$ qandaReplyType值,如:
function ExpandOptionType($option,$qandaReplyType)
Saludos;)