与其他问题的逻辑不同。
时,我会收到错误消息。
问题:世界上有多少人?
选项:{'opt1':'4 Billion','opt2':'5 Billion','opt3':'6
Billion','opt4':'7 Billion'}
答案:{"0":"2","1":"3"}
//正确答案:2和3.选项
(多个)
代码
$options = json_decode($quiz->options);
$answers = json_decode($quiz->answerOfQuestion, true);
foreach ($options as $key => $firstvalue) {
if (in_array(substr($key, -1), $answers)) {
// correct options
echo "<input type='checkbox' value='".substr($key, -1)."'>";
} else {
// wrong options
echo "<input type='checkbox' value='".substr($key, -1)."'>";
}
}
我做了什么?
$options = shuffle(json_decode($quiz->options));
$answers = shuffle(json_decode($quiz->answerOfQuestion, true));
错误:
Unknown error type: [8] Only variables should be passed by reference
Unknown error type: [2] shuffle() expects parameter 1 to be array, object given
Unknown error type: [8] Only variables should be passed by reference
Unknown error type: [2] Invalid argument supplied for foreach()
如何编写复杂的文字shuffle
?
答案 0 :(得分:0)
错误消息很不言自明。您不能将值传递给shuffle
,而只能传递变量。其次,shuffle
接受一个数组,而不是一个对象,因此,当您json_decode($options)
时,需要传递true
作为第二个参数,以使其返回数组。请注意,由于您的$options
是一个关联数组,因此shuffle
对您不起作用,因为它会使用数字键重新索引该数组。相反,您可以使用uasort
对其进行随机播放:
$answers = '{"0":"2","1":"3"}';
$answers = json_decode($answers, true);
$options = '{"opt1":"4 Billion","opt2":"5 Billion","opt3":"6 Billion","opt4":"7 Billion"}';
$options = json_decode($options, true);
uasort($options, function ($a, $b) {
return rand(-1, 1);
});
foreach ($options as $key => $value) {
echo $value;
if (in_array(substr($key, -1), $answers)) {
// correct options
echo "<input type='checkbox' value='".substr($key, -1)."'>" . PHP_EOL;
} else {
// wrong options
echo "<input type='checkbox' value='".substr($key, -1)."'>" . PHP_EOL;
}
}
输出(随机):
4 Billion<input type='checkbox' value='1'>
5 Billion<input type='checkbox' value='2'>
7 Billion<input type='checkbox' value='4'>
6 Billion<input type='checkbox' value='3'>