如何从数组中随机取样,将它们混洗并将它们放入一个新的数组中以格式化为列表

时间:2013-08-16 20:07:02

标签: php arrays list for-loop

previous question中我没有意识到我自己无法添加其余的更改,所以这就是我正在使用的内容。用户webfix帮我解决了这个问题:

$mars = array ('How big is Mars?', 'How many moons does Mars have?', 'How far away is Mars?', 'What is the highest point on Mars?');
$jupiter = array ('How big is Jupiter?', 'How many moons does Jupiter have?', 'How far away is Jupiter?', 'What is the highest point on Jupiter?');
$earth = array ('How big is Earth?', 'How many moons does Earth have?', 'How far away is Earth?', 'What is the highest point on Earth?');
$sun = array ('How big is the Sun?', 'How many moons does the Sun have?', 'How far away is the Sun?', 'What is the highest point on the Sun?');

$all = array($mars, $jupiter, $earth, $sun);

function createList($a)
{
echo "<ul>";    
foreach ($a as $array) 
    {
    $questions = count($array);
    $idquestion = rand(0, $questions-1);
    echo "<li>" . $array[$idquestion]  . "</li>";
    }
echo "</ul>";
}

createList($all);

我现在想要添加一个问题顺序的随机化,以及最多三个(或以后要改变的任何数字)问题吐出来。

它目前将选择每个问题中的一个($ mars,$ jupiter,$ earth,$ sun),然后按顺序将其列入一个列表。我希望订单是随机的,只能选择其中的三个。

我尝试使用“shuffle($ all)”,但这不起作用,也许我们可以使用类似“for($ i = 1; $ i&lt; 4; $ i ++)”来制作它摘三后停下来?感谢。

1 个答案:

答案 0 :(得分:1)

shuffle($all)应该有效(对我有用),我不知道为什么它不适合你。要选择三个,请执行:

$mars = array ('How big is Mars?', 'How many moons does Mars have?', 'How far away is Mars?', 'What is the highest point on Mars?');
$jupiter = array ('How big is Jupiter?', 'How many moons does Jupiter have?', 'How far away is Jupiter?', 'What is the highest point on Jupiter?');
$earth = array ('How big is Earth?', 'How many moons does Earth have?', 'How far away is Earth?', 'What is the highest point on Earth?');
$sun = array ('How big is the Sun?', 'How many moons does the Sun have?', 'How far away is the Sun?', 'What is the highest point on the Sun?');

$all = array($mars, $jupiter, $earth, $sun);
shuffle($all);

function createList($a)
{
  echo "<ul>"; 
  $count = 1;

  foreach ($a as $array) 
    {
      $questions = count($array);
      $idquestion = rand(0, $questions-1);
      echo "<li>" . $array[$idquestion]  . "</li>";
      if ($count++ >= 3) {
        break;
      }
    }
  echo "</ul>";
}

createList($all);

break提前终止循环。

DEMO