以同样的方式洗牌数组,按数字排列


Shuffling Array in the same way, according to number

我正在运行一个测验制作网站。我希望以打乱的顺序向用户显示问题的答案。

我试图避免存储答案呈现给用户的顺序,如果我随机洗牌的话。

我想对答案进行可预测的洗牌,以便我可以稍后以相同的方式重复洗牌(在显示结果时)。

我想我可以按一定的数字来洗牌答案列表(要么使用排序中的数字,要么通过ID号来识别多种类型的排序)。通过这种方式,我可以简单地存储它们被洗牌的数字,并召回该数字以重新洗牌它们到相同的顺序。

这是到目前为止我所拥有的框架,但我没有任何逻辑将答案以洗牌顺序放回$shuffled_array中。

<?php
function SortQuestions($answers, $sort_id)
{
    // Blank array for newly shuffled answer order
    $shuffled_answers = array();
    // Get the number of answers to sort
    $answer_count = count($questions);
    // Loop through each answer and put them into the array by the $sort_id
    foreach ($answers AS $answer_id => $answer)
    {
        // Logic here for sorting answers, by the $sort_id
        // Putting the result in to $shuffled_answers
    }
    // Return the shuffled answers
    return $shuffled_answers;
}

// Define an array of answers and their ID numbers as the key
$answers = array("1" => "A1", "2" => "A2", "3" => "A3", "4" => "A4", "5" => "A5");
// Do the sort by the number 5
SortQuestions($answers, 5);
?>

是否有技术,我可以使用洗牌的数字传递到函数的答案?

PHP的shuffle函数使用与srand一起给定的随机种子,因此您可以为此设置一个特定的随机种子。

同样,shuffle方法改变了数组键,但这可能不是最好的结果,所以您可以使用不同的shuffle函数:

function shuffle_assoc(&$array, $random_seed) {
    srand($random_seed);
    $keys = array_keys($array);
    shuffle($keys);
    foreach($keys as $key) {
        $new[$key] = $array[$key];
    }
    $array = $new;
    return true;
}

这个函数将保留原来的键,但是顺序不同。

可以将数组旋转一个因子

$factor = 5;
$numbers = array(1,2,3,4);
for ( $i = 0; $i < $factor; $i++ ) {
    array_push($numbers, array_shift($numbers));
}
print_r($numbers);

因子可以随机化,函数可以通过旋转数组将数组切换回原位

这是一种可能的方法。

$result = SortQuestions($answers, 30);
print_r($result);

function SortQuestions($answers, $num)
{
$answers = range(1, $num);
shuffle($answers);
return $answers;
}