随机数组元素保留关联键值对

时间:2014-03-18 08:05:13

标签: php arrays

我正在构建一个测验应用程序。挺直的。只留下最后一点,我被卡住了。我想随机选择答案。检查查看我在CAPS中遇到问题的代码中的注释。 Shuffle正在工作,但它将assoc数组更改为数字0 1等。 array_rand使foreach不工作和foreach抛出错误。提供的参数无效。 不知道出了什么问题,任何人都可以帮助我..

        <form action="<?php echo URL?>load=quiz&page=<?php echo $page; ?>" method="post" name="quiz">
        <?php //var_dump($quiz_data); 
            $all_ans_opts = array();
            $ans_opts = array_filter($all_ans_opts);;


        ?>
        <?php foreach($quiz_data as $d):

                $all_ans_opts['answer_a'] = $d['answer_a'];
                $all_ans_opts['answer_b'] = $d['answer_b'];
                $all_ans_opts['answer_c'] = $d['answer_c'];
                $all_ans_opts['answer_d'] = $d['answer_d'];
                $all_ans_opts['answer_e'] = $d['answer_e'];

       ?>
        <!-- If the question type is MC show the radio form-->


        <p>                    
        Question <?php echo $d['question_number']; ?>: <?php echo $d['question_title'] ; ?>
        </p>
        <p>
           <input type="hidden" name="page_num" value="<?php echo $page; ?>">
           <input type="hidden" name="question_number" value="<?php echo $d['question_number']; ?>">
           <input type="hidden" name="questionid" value="<?php echo $d['questionid']; ?>">
           <input type="hidden" name="quiz_number" value="<?php echo $d['quiz_number']; ?>">

        <?php
        endforeach; 

        //var_dump($all_ans_opts);



            ?>
               <?php 
// HERE I AM TRYING TO RANDAMISE THE ARRAY ELEMENTS PRESERVING KEY VALUE PAIRS FOR FOREACH
// FOR RANDAMISATION IF I USE SHUFFLE IT WORKS BUT CHANGING THE KEY FROM ASSOCIATIVE TO //INDEX 0 1 ETC.. 
// IF I USE ARRAY_RAND FUNCTION FOREACH GIVES ERROR- nvalid argument supplied for foreach()

               $ans_opts = array_filter($all_ans_opts);
               shuffle($all_ans_opts);                     
               //$ans_opts = array_rand($all_ans_opts);

           ?>

           <?php foreach ($ans_opts as $key=>$val){ ?>

            <input type="radio" name="<?php echo 'answer_selected';?>" value=<?php echo $key ?>><?php echo $val; ?><br/>

           <?php } ?>
        </p>


        <input type="submit" name="prev" value="Previous Question" <?php if($page == 0) echo "disabled";?> />                
        <input type="submit" name="save" value="<?php if($page == $totalQuestion-1)echo 'Submit Quiz'; else{echo 'Save & Continue';} ?>" />
        <input type="submit" name="next" value="Next Question" <?php if($page == $totalQuestion-1) echo "disabled";?> />
    </form>  

2 个答案:

答案 0 :(得分:1)

简单的方法是使用uasort() - 它在排序时保留密钥。要随机化,只需使用随机排序:

$array = [
  'foo'=>14,
  'bar'=>10,
  'baz'=>19,
  'bee'=>26,
  'feo'=>23
];

uasort($array, function($x,$y)
{
   //you can use `return mt_rand(0,1)` - but that's
   //unreliable, since compare function must return -1/0/1
   return mt_rand() - mt_rand();
});

答案 1 :(得分:0)

我在手册中找到了一个功能:

http://pl1.php.net/shuffle#94697