简体   繁体   中英

Shuffling a table using Javascript or PHP

I am new to Javascript and PHP and I am practicing to build a quiz where the choices are randomized. I'm just wondering if you can shuffle or randomize all that is inside a row of a table? Is it Possible to randomize This each line all together?

1.<tr><td > <input type="radio" name="answer" value="optiona">a</input> </td></tr>
2.<tr><td > <input type="radio" name="answer" value="optionb">b</input> </td></tr>
3.<tr><td > <input type="radio" name="answer" value="optionc">c</input> </td></tr>
4.<tr><td > <input type="radio" name="answer" value="optiond">d</input> </td></tr>

My question is.. is it possible to randomize the 4 rows in PHP or JavaScript everytime I refresh the page or someone takes the quiz?

It would be easiest to do this in PHP.

Simply do shuffle($array);

Documentation for shuffle()

Seeing the comment under Mister Dood's answer, I should warn that stuffing HTML in an array is suboptimal, as you lose the ability to manipulate it easily. Try this:

$array = array(
  "a" => "Answer A",
  "b" => "Answer B",
  "c" => "Answer C",
  "d" => "Answer D"
);

shuffle($array);

$count = 0;
foreach ($array as $value => $text) {
  ?><tr><td><?php
    echo ++$count;
  ?></td><td><label for="answer<?php
    echo $value;
  ?>"><input type="radio" name="answer" id="answer<?php
    echo $value;
  ?>" value="<?php
    echo $value;
  ?>"><?php
    echo $text;
  ?></label></td></tr><?php
}

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