使用相同的随机变量返回2个不同的数组

时间:2017-01-03 16:33:05

标签: php arrays return

我试图使用相同的随机变量返回2个不同的数组。所以我有:

function TransTest() {
    $TransQ = array();
    $TransA = array();

    $TransQ[0] = "Q1";
    $TransQ[1] = "Q2";
    $TransQ[2] = "Q3";
    $TransQ[3] = "Q4";    

    $TransA[0] = "Ans 1";
    $TransA[1] = "Ans 2";
    $TransA[2] = "Ans 3";
    $TransA[3] = "Ans 4";    

    $index = rand(0, count($TransQ)-1);

    return $TransQ[$index];
}

所以这基本上会从$TransQ数组返回一个随机问题。我想做的是回答问题的相应答案。

类似于:

return ($TransQ[$index] && $TransA[$index]);

但这似乎不起作用。请帮忙。

1 个答案:

答案 0 :(得分:2)

只需返回一个数组:

return array($TransQ[$index], $TransA[$index]);

然后访问:

$result = TransTest();
echo $result[0] . ' is ' . $result[1];

或关联:

return array('q' => $TransQ[$index], 'a' => $TransA[$index]);

然后:

$result = TransTest();
echo $result['q'] . ' is ' . $result['a'];

或者在上述每种情况中:

list($question, $answer) = TransTest();
echo $question . ' is ' . $answer;

另一种方式(可能不是您的最佳选择),是使用引用&

function TransTest(&$q=null, &$a=null) {
    //code
    $q = $TransQ[$index];
    $a = $TransA[$index];
}

然后:

TransTest($question, $answer);
echo $question . ' is ' . $answer;
相关问题