我正在使用以下内容选择一组没有任何重复的随机问题:
<?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');
有一个是/否下拉列表。选择“是”的问题总是必须纳入上面的循环中。
E.g该测试有20个问题可供选择,10个将随机选择。在20个问题中,有2个必需的问题(即将始终选择这些问题)。所以它需要抓住2个必要的问题并选择其他8个随机问题。
如何在随机选择中包含所需的问题?
答案 0 :(得分: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
答案 1 :(得分:3)
该问题没有说明,但所有人都建议使用Advanced Custom Fields进行Repeater Add-on设置。
在这种情况下,这是我完成的测试配置:
请注意,我在这里使用$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>";
}