Partly shuffle php array

Discussion in 'PHP' started by Hemant Agarwal, Aug 10, 2010.

  1. #1
    Hi,

    I have an array $quest


    for ( $count = 0; $count <= 99; $count++)
    {
    $quest[$count]=mysql_fetch_array($result,MYSQL_NUM);;

    }

    $quest is a 2d array.For instance

    $quest[0][0] contains a question
    $quest[0][1] to $quest[0][5] each contains an answer choice for the question
    only one of which is correct.

    I want to randomly shuffle all the answer choices($quest[0][1] to $quest[0][5]) but let the question remain at $quest[0][0]).How can I do that?
    I know there is a function called shuffle() but shuffle(),shuffles the entire array.I just want to shuffle all elements of a particular array except for the first one.



    Thanks
    Hemant
     
    Last edited: Aug 10, 2010
    Hemant Agarwal, Aug 10, 2010 IP
  2. MyVodaFone

    MyVodaFone Well-Known Member

    Messages:
    1,048
    Likes Received:
    42
    Best Answers:
    10
    Trophy Points:
    195
    #2
    Thats true, but you can limit the shuffle excluding 0 so it will be 1-5, something like this, might help:

    
    <?php
    
    $quest[0][0] = "Question";
    $quest[0][1] = "Answer 1";
    $quest[0][2] = "Answer 2";
    $quest[0][3] = "Answer 3";
    $quest[0][4] = "Answer 4";
    $quest[0][5] = "Answer 5";
    
    
    echo $quest[0][0];
    
    $answer = range(1, 5);
    shuffle($answer);
    foreach ($answer as $answer) {
        echo "<br />",$quest[0][$answer];
    }
    
    ?>
    
    PHP:
    Will echo out:
    Question
    Answer 2
    Answer 1
    Answer 3
    Answer 4
    Answer 5 
    Code (markup):
     
    Last edited: Aug 10, 2010
    MyVodaFone, Aug 10, 2010 IP
  3. woogley

    woogley Peon

    Messages:
    103
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    You can try this..

    
    <?php
    
    $_quest = $quest;
    $quest = array();
    
    foreach($_quest as $idx=>$q){
      shuffle($q);
      $quest[$idx] = $q;
    }
    
    ?>
    
    Code (markup):
     
    woogley, Aug 10, 2010 IP
  4. joebert

    joebert Well-Known Member

    Messages:
    2,150
    Likes Received:
    88
    Best Answers:
    0
    Trophy Points:
    145
    #4
    You should really modify the code that builds the array to begin with if you can. This however, will work with an existing array.

    <pre><?php
    
    $quest = array(
    	array(
    		'Question One',
    		'Answer 1:1',
    		'Answer 1:2',
    		'Answer 1:3',
    		'Answer 1:4',
    		'Answer 1:5',
    	),
    	array(
    		'Question Two',
    		'Answer 2:1',
    		'Answer 2:2',
    		'Answer 2:3',
    		'Answer 2:4',
    		'Answer 2:5',
    	),
    );
    
    foreach($quest as &$_quest)
    {
    	$q = array_shift($_quest);
    	shuffle($_quest);
    	array_unshift($_quest, $q);
    }
    
    print_r($quest);
    
    ?></pre>
    PHP:
     
    joebert, Aug 11, 2010 IP