【问题标题】:How I can shuffle multiple JSON data in foreach? (PHP)如何在 foreach 中打乱多个 JSON 数据? (PHP)
【发布时间】:2019-05-30 23:03:49
【问题描述】:

这和其他问题的逻辑不一样。


有两个 JSON 数据。我想确保问题的答案以复杂的形式编写。但我做不到。我可以得到一个 JSON,但是当有多个 JSON 时我得到错误
  • 问题:世界上有多少人?

  • 选项:{'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

【问题讨论】:

  • 如果您想使用数组,您需要将true 作为第二个参数传递给您的 json_decode 函数。否则你会得到一个对象。您正在为 answerOfQuestion 而不是选项这样做。在结果上尝试var_dump() 以帮助您解决问题

标签: php arrays json shuffle


【解决方案1】:

错误消息是不言自明的。您不能将值传递给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'>

Demo on dbfiddle

【讨论】:

  • @J.Doe3 不用担心。我很高兴能帮上忙。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-09
  • 2012-06-30
  • 1970-01-01
  • 2018-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多