Is it possible to randomize data from a JSON?

Asked

Viewed 67 times

0

I am making a quiz system, where the correct answer will always be the first alternative in the database, but it is necessary that it be random when it comes to answering. (PHP)

It is possible to randomize the data within alternatives?

"questions": [{
    "title": "Qual é a raça de Goku?",
    "image": {
        "path": ""
    },
    "alternatives": [{
        "title": "Sayajins",
        "image": {
            "path": ""
        },
        "correct": true
    }, {
        "title": "Anjo",
        "image": {
            "path": ""
        }
    }, {
        "title": "Android",
        "image": {
            "path": ""
        }
    }],
    "alternativeType": 1
}

1 answer

0

You can use a PHP function called shufle(https://www.php.net/manual/en/function.shuffle.php).

With the shuffle function you can shuffle the elements of an array, in this case, shuffling the alternatives of the questions.

You can do it this way:

<?php

$questions = [
    [
        "title" => "Qual é a raça de Goku?",
        "image" => [
            "path" => "",
        ],
        "alternatives" => [
            [
                "title" => "Sayajins",
                "image" => [
                    "path" => "",
                ],
                "correct" => true,
            ], [
                "title" => "Anjo",
                "image" => [
                    "path" => "",
                ],
            ], [
                "title" => "Android",
                "image" => [
                    "path" => "",
                ],
            ],
        ],
        "alternativeType" => 1,
    ],
];

array_map(function ($question) {
    shuffle($question['alternatives']);
}, $questions);

So you go through all the questions and shuffle(suffle), the alternatives, leaving items randomly ordered.

I hope I’ve helped!

  • As much as it generates the expected result, it is mistakenly using the function array_map. Such a function, as the name says, has been defined to define a relationship between the input value and output values, also known as a map; what you want to do is to traverse the array and call the function shuffle. The function array_map is no use to traverse array, for such you use array_walk or some loop of repetition.

  • @Andersoncarloswoss and to check if correct exists is and equal to true?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.