将额外的循环纳入随机选择?

时间:2012-09-24 10:25:44

标签: php wordpress custom-fields

我的代码是从Wordpress中选择一组随机问题。

<?php
    $rows = get_field('step_by_step_test');
    $row_count = count($rows);
    $rand_rows = array();
    $questions = get_field('select_number_of_questions');
    for ($i = 0; $i < min($row_count, $questions); $i++) {
        $r = rand(0, $row_count - 1);
        while (array_search($r, $rand_rows) !== false) {
            $r = rand(0, $row_count - 1);
        }
        $rand_rows[] = $r;
        echo $rows[$r]['question'];
    }
?>

我想加入一些额外的代码(下面),我如何确保它选择相同的随机问题?

<?php if(get_sub_field('answer_options')): ?>
<?php while(has_sub_field('answer_options')): ?> 
    <?php echo the_sub_field('answer'); ?>
<?php endwhile; ?> 
<?php endif; ?>

3 个答案:

答案 0 :(得分:3)

为什么不稍微改变你的做法?

<?php 
   $rows = get_field('step_by_step_test');  // Get the test
   $question_count = get_field('select_number_of_questions');  // Get the number of questions
   $rows = shuffle($rows);   // Randomize your questions
   $rows = array_slice($rows, $question_count);   // Now set the array to only contain the number of questions you wanted
   foreach ($rows as $row) {
       echo $row['question'];    // Show the question
       if(get_sub_field('answer_options', $row['id'])) {
              while(has_sub_field('answer_options', $row['id'])) {
                       echo the_sub_field('answer');
              }
       }
   } 
?>

我假设您可以更改“get_sub_field”以包含问题的ID,因此您可以在“answer_options”的“where”字段中包含该ID。这将允许您链接问题。

答案 1 :(得分:1)

我认为你需要的是在循环中设置整个事物。 query by custom field

或者你可以存储上面提到的问题的ID,然后是query for the answers for those specific posts

答案 2 :(得分:0)

以下是我使用高级自定义字段插件+ Royal Slider随机化我的WordPress滑块以及上面的TheSwiftExchange代码的修改版本

<div id="full-width-slider" class="royalSlider heroSlider rsMinW">

<?php
   /*
    *  Slider Repeater field shuffled
    *  http://stackoverflow.com/questions/12563116/incorporating-extra-loop-into-random-selection
    */


    $rows = get_field('slider');
//  For Debugging:
//  echo "<pre>";
//  var_dump($rows);
//  echo "</pre>";

    $quotes = get_field('slide_text');  // Get the number of images
    shuffle($rows);   // Randomize your slides

    foreach ($rows as $row) {

        $slideImageID =  $row['slide_image'];
        $slideImage = wp_get_attachment_image_src( $slideImageID, 'full' );
        $slideText = $row['slide_text'];
        ?>

        <div class="rsContent">

               <div class="royalCaption">
                   <div class="royalCaptionInner">

                       <div class="infoBlock">
                            <?php if(!empty($slideText)) {
                                   echo $slideText;
                           }; ?>
                       </div>
                   </div>
               </div>
               <img src="<?php echo $slideImage[0]; ?>" class="" />

        </div><!-- /.rsContent -->
    <?php }  // end foreach ?>

</div><!-- /slider-wrap -->