Follow-up question: How to randomly take some examples from arrays, shuffle them and place them into a new array to be formatted as a list
How do you store random parts of an array within an array and then print as a list?
I know that there are answers to both parts of my question already, but the two answers I found aren't compatible with each other. I'm trying to do this with PHP, but i'm willing to use another code language if absolutely necessary.
I made up a simple version of what I've tried to do so far. I would like to store one random question from each array ($mars, $jupiter and $earth) as another array ($all) and then reformat this array as a list to be displayed as html (using < ul > and < li >).
For some reason, the first function wants the =>array(), but the second doesn't.
This makes a formatted html-style list from an array (replace $all with the array you want to format)
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;
}
Here I'm just making the arrays. The =>array() is needed for the formatting above. I don't know why.
$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);
This prints the formatted version of $all
echo makeList ($all);
This is randomly taking two questions from the array $marz and printing them
$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]] . "
";
echo $marz[$rand_keys[1]] . "
";
Here I am storing these results in a new array and printing it as proof in ugly array form
$new = array ($marz[$rand_keys[0]], $marz[$rand_keys[1]]);
print_r ($new);