【问题标题】:using array_rand rather than shuffle in PHP在 PHP 中使用 array_rand 而不是 shuffle
【发布时间】:2020-01-27 09:40:19
【问题描述】:

我正在使用来自 grade.php 的代码。我想使用array_Rand 而不是使用随机播放。有人可以帮忙吗?

代码运行良好,但我想显示 20 个问题中的 10 个,因此使用 shuffle() 并不是我真正想要的。如果能得到任何帮助,我将不胜感激,在此先感谢您!

编辑:我添加了 Array_slice,现在显示错误:

未定义索引:问题@第 77 行

【问题讨论】:

  • 您可以使用array_slice 来获取前10 个随机问题吗? php.net/manual/en/function.array-slice.php
  • array_rand($Questions, 10);...
  • @jibsteroos 是的,我试过了,但我不知道如何操作 foreach 循环。请多多指教!
  • @benJ 在回显问题和选项时,我需要编辑 foreach 循环吗?因为我在那里操作代码时遇到了麻烦。请指教。谢谢
  • @benJ 我试过了,我得到 **Undefined index: Questions at line 77 ** 我已经编辑了有问题的代码,请检查。

标签: php arrays random


【解决方案1】:

您可以选择 Id,然后与原始数组相交。这是一个随机选择两个的示例:

<?php    
$questions = array(
    1 => array(
        'Question' => '1. CSS stands for',
        'Answers' => array(
            'A' => 'Computer Styled Sections',
            'B' => 'Cascading Style Sheets',
            'C' => 'Crazy Solid Shapes'
        ),
        'CorrectAnswer' => 'B'
    ),
    2 => array(
        'Question' => '2. What is the Capital of the Philippines',
        'Answers' => array(
            'A' => 'Cebu City',
            'B' => 'Davao City',
            'C' => 'Manila City'
        ),
        'CorrectAnswer' => 'C'
    ),
    3 => array(
        'Question' => '3. What is black and white',
        'Answers' => array(
            'A' => 'A Zebra',
            'B' => 'A Sycamore Tree',
            'C' => 'Law'
        ),
        'CorrectAnswer' => 'A'
    )
);

$rand_ids       = array_rand($questions, 2);
$rand_questions = array_intersect_key($questions, array_flip($rand_ids));

【讨论】:

  • 提交表单后,从您提交的答案中获取密钥(与此处的 ID 有关),您可以使用它们与您的问题数组相交以获得相同的子集。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-05
  • 1970-01-01
  • 2018-03-20
  • 1970-01-01
  • 2018-03-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多