按照数字以相同的方式改组数组 [英] Shuffling Array in the same way, according to number

查看:92
本文介绍了按照数字以相同的方式改组数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行一个问答游戏网站.我希望以随机的顺序向用户显示问题的答案.

I am running a quiz making website. I wish to show the answers to a question to a user in a shuffled order.

如果我要随机洗净答案,我将尝试避免存储答案呈现给用户的顺序.

I'm trying to avoid storing the order that answers were presented to the user, if I were to shuffle them randomly.

我想按预期的方式随机播放答案,以便以后以后可以以相同的方式重复随机播放(在显示结果时).

I want to shuffle the answers predictably, so that I can repeat the shuffle in the same way later (when displaying results).

我认为我可以按一定的数字(在排序中使用数字,或通过ID编号识别多种类型的排序)对答案列表进行排序.这样,我可以简单地存储对其改组的编号,并调出该编号以将它们重新改组为相同顺序.

I've thought that I could shuffle the list of answers by a certain number (either using the number within the sort, or having multiple types of sorts identifiable by an ID number. This way I can simply store the number that they were shuffled by and recall that number to reshuffle them again to the same order.

这是我到目前为止所掌握的内容,但是我没有任何逻辑可以将答案按重新排列的顺序放回到$ shuffled_array中.

Here's the skeleton of what I have so far, but I don't have any logic to put the answers back in the $shuffled_array in the shuffled order.

<?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);

?>

是否可以通过传递给函数的数字来整理答案?

Is there technique that I can use to shuffle the answers by the number passed into the function?

推荐答案

PHP的随机播放函数使用 srand 给出的随机种子,因此您可以设置特定的随机种子.

PHP's shuffle function uses the random seed given with srand, so you can set a specific random seed for this.

此外,shuffle方法的更改是数组键,但这对您来说可能不是最好的结果,因此您可以使用其他shuffle函数:

Also, the shuffle method change's the array keys, but this is probably not the best outcome for you, so you may use a different shuffle function:

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;
}

此功能将保留原始键,但顺序不同.

This function will keep the original keys, but with a different order.

这篇关于按照数字以相同的方式改组数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆