PHP数组随机有两个输出


PHP array random with two Output

我想用随机的原则来回答和提问。我的输出有问题。

你能帮我吗?

<?  
$Expos['u1'][1]=('question 1') . ('answer 1');
$Expos['u1'][2]=('question 2') . ('answer 2');
$Expos['u1'][3]=('question 3') . ('answer 3');

$Expos['u2'][1]=('question 4') . ('answer 4');
$Expos['u2'][2]=('question 5') . ('answer 5');
$Expos['u2'][3]=('question 6') . ('answer 6');

function array_multi_rand($Zoo){
    $Boo=array_rand($Zoo);
    if(is_array($Zoo[$Boo])){
        return array_multi_rand($Zoo[$Boo]);
    }else{
        return $Zoo[$Boo];
    }
}
echo ('<h1>') . (array_multi_rand($Expos)) . ('</h1>'); /* QUESTION (how the write this part)*/
echo '<button class="show">Show Answer</button>';
echo ('<p>') . (array_multi_rand($Expos)) . ('</p>'); /* ANSWER (how the write this part)*/
?>

您应该在数组中的问题和答案之间添加一些特殊字符,这些字符既不会出现在问题中,也不会出现在答案中,或者创建关联数组。

示例:

<?php
$Expos['u1'][1]=('question 1') . '#'. ('answer 1');
$Expos['u1'][2]=('question 2') . '#'. ('answer 2');
$Expos['u1'][3]=('question 3') . '#'. ('answer 3');

$Expos['u2'][1]=('question 4') . '#'. ('answer 4');
$Expos['u2'][2]=('question 5') . '#'. ('answer 5');
$Expos['u2'][3]=('question 6') . '#'. ('answer 6');

function array_multi_rand($Zoo){
    $Boo=array_rand($Zoo);
    if(is_array($Zoo[$Boo])){
        return array_multi_rand($Zoo[$Boo]);
    }else{
        return $Zoo[$Boo];
    }
}
mb_internal_encoding('UTF-8');
$selected = explode('#', array_multi_rand($Expos));

echo ('<h1>') . $selected[0] . ('</h1>'); 
echo '<button class="show">Show Answer</button>';
echo ('<p>') . $selected[1] . ('</p>'); 
?>

多维数组的例子(注意函数array_multi_rand被改变了一点):

<?php
$Expos['u1'][1]= array( 'q' => 'question 1', 'a' => 'answer 1');
$Expos['u1'][2]=array( 'q' => 'question 2', 'a' => 'answer 2');
$Expos['u1'][3]=array( 'q' => 'question 3', 'a' => 'answer 3');

$Expos['u2'][1]=array( 'q' => 'question 4', 'a' => 'answer 4');
$Expos['u2'][2]=array( 'q' => 'question 5', 'a' => 'answer 5');
$Expos['u2'][3]=array( 'q' => 'question 6', 'a' => 'answer 6');

function array_multi_rand($Zoo){
    $Boo=array_rand($Zoo);
    if(is_array($Zoo[$Boo]) && !isset($Zoo[$Boo]['q']) &&  !isset($Zoo[$Boo]['a'])){
        return array_multi_rand($Zoo[$Boo]);
    }else{
        return $Zoo[$Boo];
    }
}
mb_internal_encoding('UTF-8');
$selected =  array_multi_rand($Expos);

echo ('<h1>') . $selected['q'] . ('</h1>'); 
echo '<button class="show">Show Answer</button>';
echo ('<p>') . $selected['a'] . ('</p>'); 
?>