【问题标题】:Returning 2 different arrays using the same random variable使用相同的随机变量返回 2 个不同的数组
【发布时间】:2017-01-03 16:33:05
【问题描述】:

我正在尝试使用相同的随机变量返回 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]);

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

【问题讨论】:

  • return ['Question' => $TransQ[$index], 'Answer' => $TransA[$index]];

标签: php arrays return


【解决方案1】:

只返回一个数组:

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;

【讨论】:

  • 非常感谢您的全面回答,这非常有效!感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2018-09-23
  • 1970-01-01
  • 2010-12-10
  • 2021-05-07
  • 1970-01-01
  • 2021-11-11
  • 1970-01-01
  • 2023-03-18
相关资源
最近更新 更多