2013-03-26 83 views
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個其他隨機問題。

如何在隨機選擇中包含所需的問題?

+0

問題如何與'required'字段相關聯?我們能看到表格嗎? – xpy 2013-03-31 17:12:16

+0

正如我所見,這是一系列問題,所以您可以簡單地請求所需的問題並將它們添加到數組中 – ahmad 2013-04-03 20:24:35

回答

3

的問題沒有說明,但一切都表明這是一個Advanced Custom Fields使用Repeater Add-on設置。

在這種情況下,這是測試配置我做:

acf config

請注意,這裏我使用$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>"; 
} 
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) { 
    ... 
} 

希望我再幫你:對

+0

我已對您的答案進行了編輯,它現在包含正確的必填字段代碼,但它仍未包括隨機選擇的5個必需的問題。 – Rob 2013-03-26 16:30:16

+0

'get_field(「required_question」)'沒有指定哪個問題。我不確定我明白你的'get_field'函數是如何工作的... – 2013-03-26 16:31:09

+0

get_field(「required_question」)只是抓住WordPress中的問題是否需要(下拉可以是或不是)。這就是爲什麼我認爲它需要像if(get_field(「required_question」)==「是」)。我想只是把它當作一個可以有或沒有值的變量。 – Rob 2013-03-27 09:51:15