如何在 foreach 中随机播放多个 JSON 数据? (PHP)

How I can shuffle multiple JSON data in foreach? (PHP)

和其他问题的逻辑不一样


有两个 JSON 数据。我想确保问题的答案以复杂的形式书写。但我做不到。我可以得到一个 JSON,但当有多个 JSON

时,我会收到错误消息

代码

   $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

错误消息相当 self-explanatory。您不能将值传递给 shuffle,只能传递一个变量。其次,shuffle接受一个数组,而不是一个对象,所以当你json_decode($options)时,你需要传递true作为第二个参数,使它return成为一个数组。请注意,因为您的 $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'>

Demo on dbfiddle