7

我正在使用以下内容选择一组没有任何重复的随机问题:

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

每个问题都有一个字段:get_field('required_question');有一个是/否下拉菜单。选择“是”的问题总是必须合并到上面的循环中。

例如,该测试有 20 个问题可供选择,随机选择 10 个。在 20 个问题中,有 2 个必填问题(即这些问题将始终被选中)。所以它需要抓住 2 个必填问题并选择 8 个其他随机问题。

如何在随机选择中包含必填问题?

4

2 回答 2

3

问题没有说明,但都表明这是使用Repeater Add-on设置的高级自定义字段

在这种情况下,这是我所做的测试配置:

acf 配置

请注意,我在这里使用$repeater_row['title']而不是 OP 的$repeater_row['question']. 另外,我删除了该answer_options部分。详情见评论:

// Get fields
$amount = get_field( 'select_number_of_questions' );
$repeater = get_field( 'step_by_step_test' );

// Auxiliary arrays to separate fields by Field Name
$not_enabled = array();
$enabled = array();

// Separate
foreach( $repeater as $field )
{
    if( 'no' == $field['enabled'] )
        $not_enabled[] = $field;
    else
        $enabled[] = $field;
}

// Discount the enabled from the the total amount
$amount = (int)$amount - count( $enabled );

// Shuffle before slicing
shuffle( $not_enabled );
$repeater_limit = array_slice( $not_enabled, 0, $amount );

// Add enabled fields and shuffle again
$final_array = array_merge( $repeater_limit, $enabled ); 
shuffle( $final_array );

foreach( $final_array as $repeater_row ) {
    echo "<p>" . $repeater_row['title'] . "</p>";
}
于 2013-04-03T15:21:17.027 回答
3

首先,您需要过滤掉所需的问题,如下所示:

$all_questions = get_field("step_by_step_test");
$required = $optional = array();
foreach($all_questions as $question) {
    if( $a['required_question']) $required[] = $question;
    else $optional[] = $question;
}
$amount = get_field("select_number_of_questions")-count($required);
shuffle($optional);
$final = array_merge($required,array_slice($optional,0,$amount));
foreach($final as $repeater_row) {
    ...
}

希望我再次帮助你:p

于 2013-03-26T16:11:11.287 回答