简体   繁体   中英

How do I randomize data from a json array in php?

I am pulling one random question served in json from an external source with the following php code.

$json_quesions = //URL TO PULL QUESTION;
$question = file_get_contents($json_quesions);
$data = json_decode($question, true);

Everything is working fine and by default, I can get the array of answers in php with

$option1 = $data['results'][0]['incorrect_answers'][0];
$option2 = $data['results'][0]['incorrect_answers'][1];
$option3 = $data['results'][0]['incorrect_answers'][2];
$option4 = $data['results'][0]['correct_answer'];

But I would like to randomize the options on each load so that the correct answer takes on random positions in the options. So far i have tried this but it still returns thesame values as before. Please help

$optionsarray = array("$option1","$option2","$option3","$option4");
        $random_options = array_rand($optionsarray, 3);
        
        echo $random_options[0];
        echo $random_options[1];
        echo $random_options[2];
        echo $random_options[3];

Take a look at shuffle() , https://www.php.net/manual/en/function.shuffle.php

shuffle — Shuffle an array

Description

shuffle ( array &$array ): bool
This function shuffles (randomizes the order of the elements in) an array. It uses a pseudo random number generator that is not suitable for cryptographic purposes

$optionsarray = array("$option1","$option2","$option3","$option4");
shuffle($optionsarray);
print_r($optionsarray);

Example,

$x = ['a', 'b', 'c', 'd', 'e'];
shuffle($x);
print_r($x);

/** example run output 
Array
(
    [0] => a
    [1] => d
    [2] => c
    [3] => e
    [4] => b
)
**/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM