Rob
Rob

Reputation: 6380

Matching up two foreach loops using array value

I have two foreach loops. The first grabs a load of questions from Wordpress, the second is supposed to grab the multiple answers. This is straight forward had it not involved some randomisation of the questions, which makes it confusing.

This is the two foreach loops without them being randomised.

<?php 
$repeater = get_field('step_by_step_test');
foreach( $repeater as $repeater_row ){ ?>
    <p><?php echo $repeater_row['question']; ?></p>
    <?php $rows = $repeater_row['answer_options'];
    foreach ($rows as $row){ ?>
        <?php echo $row['answer']; ?><br />
    <?php } ?>
<?php } ?>

This loops through each question and also grabs the multiple answers.

How can I incorporate it randomising the questions? This is my attempt, this works for getting a random set of questions but I'm getting an error for the answers part (invalid argument supplied for foreach).

<?php 
$amount = get_field('select_number_of_questions');
$repeater = get_field('step_by_step_test');
$random_rows = array_rand( $repeater, $amount );
echo implode(', ', $random_rows);
    foreach( $random_rows as $repeater_row ){ ?>
        <p><?php echo $repeater[$repeater_row]['question']; ?></p>
        <?php $rows = get_sub_field('answer_options');
        foreach ($rows as $row){ ?>
            <?php echo $row['answer']; ?><br />
        <?php } ?>
    <?php } ?>

I use this plugin for wordpress - http://www.advancedcustomfields.com/

Upvotes: 2

Views: 763

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324750

First I'm going to rewrite your first code block to not look like chewed cud.

<?php
$repeater = get_field("step_by_step_test");
foreach($repeater as $repeater_row) {
    echo "<p>".$repeater_row['question']."</p>";
    $rows = $repeater_row['answer_options'];
    foreach($rows as $row) {
        echo $row['answer']."<br />";
    }
}
?>

And now for the magic: Add shuffle($rows) immediately before the foreach($rows as $row) { line, and the answers will appear in random order.

EDIT in response to comments: Start your code like this:

$repeater = get_field("step_by_step_test");
shuffle($repeater);
$repeater_limit = array_slice($repeater,0,5);
foreach($repeater_limit as $repeater_row) {
    ....

Upvotes: 3

Related Questions