如何在数组中存储数组的随机部分,然后作为列表打印?

时间:2013-08-14 20:48:13

标签: php arrays

后续问题:How to randomly take some examples from arrays, shuffle them and place them into a new array to be formatted as a list

如何在数组中存储数组的随机部分,然后作为列表打印?

我知道我的问题的两个部分都有答案,但我找到的两个答案彼此不兼容。我试图用PHP做到这一点,但如果绝对必要,我愿意使用另一种代码语言。

我编写了一个迄今为止我尝试过的简单版本。我想将每个数组($ mars,$ jupiter和$ earth)中的一个随机问题存储为另一个数组($ all),然后将此数组重新格式化为列表以显示为html(使用< ul>和< ; li>)。

出于某种原因,第一个函数需要=>数组(),但第二个函数不需要。

这会从数组中生成格式化的html样式列表(将$ all替换为要格式化的数组)

function makeList($all) {
        //Base case: an empty array produces no list
        if (empty($all)) return '';
        //Recursive Step: make a list with child lists
        $output = '<ul>';
        foreach ($all as $key => $subArray) {
            $output .= '<li>' . $key . makeList($subArray) . '</li>';
        }
        $output .= '</ul>';
        return $output;
    }

这里我只是制作阵列。上面的格式化需要=&gt; array()。我不知道为什么。

$mars = array ('How big is Mars?'=>array(), 'How many moons does Mars have?'=>array(), 'How far away is Mars?'=>array(), 'What is the highest point on Mars?'=>array());
$jupiter = array ('How big is Jupiter?'=>array(), 'How many moons does Jupiter have?'=>array(), 'How far away is Jupiter?'=>array(), 'What is the highest point on Jupiter?'=>array());
$earth = array ('How big is Earth?'=>array(), 'How many moons does Earth have?'=>array(), 'How far away is Earth?'=>array(), 'What is the highest point on Earth?'=>array());
//An array of the three arrays
$all = array ($mars, $jupiter, $earth);

这将打印$ all

的格式化版本
echo makeList ($all);

这是从数组$ marz中随机抽取两个问题并打印出来

$marz = array ('How big is Mars?', 'How many moons does Mars have?', 'How far away is Mars?', 'What is the highest point on Mars?');
$rand_keys = array_rand($marz, 2);
echo $marz[$rand_keys[0]] . "\n";
echo $marz[$rand_keys[1]] . "\n";

这里我将这些结果存储在一个新数组中,并将其打印为丑陋数组形式的证据

$new = array ($marz[$rand_keys[0]], $marz[$rand_keys[1]]);
print_r ($new);

1 个答案:

答案 0 :(得分:2)

我不知道我是否得到了你需要的东西,但我发现你的代码非常混乱,所以我从你的描述中创建了我自己的函数,这里有整个修复过的数组和所有东西

$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?');

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

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);