随机化功能可以很好地与问题随机播放数组配合使用。每次随机化工作时,如何从N中选择特定数量的数字从数组中删除。 表示如果我们希望以随机模式每次显示100个问题列表中的20%或20个问题
public function random_questions( $quiz_questions, $quiz_id ) {
if ( get_post_meta( $quiz_id, '_lp_random_mode', true ) == 'yes' ) {
// get user meta random quiz
$random_quiz = get_user_meta( get_current_user_id(), 'random_quiz', true );
if ( is_admin() || empty( $random_quiz ) || empty( $random_quiz[ $quiz_id ] ) ) {
return $quiz_questions;
}
$questions = array();
if ( array_key_exists( $quiz_id, $random_quiz ) && sizeof( $random_quiz[ $quiz_id ] ) == sizeof( $quiz_questions ) ) {
foreach ( $random_quiz[ $quiz_id ] as $question_id ) {
if ( $question_id ) {
$questions[ $question_id ] = $question_id;
}
}
} else {
$question_ids = array_keys( $quiz_questions );
shuffle( $question_ids );
$random_quiz[ $quiz_id ] = $question_ids;
$questions = array();
foreach ( $question_ids as $id ) {
$questions[ $id ] = $quiz_questions[ $id ];
}
}
return $questions;
}
return $quiz_questions;
}
答案 0 :(得分:0)
使用array_rand()
随机选择数组键,而不是将所有键与array_keys()
一起使用。这样就不必重新整理数组。
$question_ids = array_rand( $quiz_questions , 20);
$random_quiz[ $quiz_id ] = $question_ids;
$questions = array();
foreach ( $question_ids as $id ) {
$questions[ $id ] = $quiz_questions[ $id ];
}