如何将字符串转换为数组名称(php)? - php

我有4个数组,每个数组都有一个问题和答案。我想选择一个随机的问题/答案数组。这是我的代码:

<?php
$query_1 = array("What is two plus three?", "5");
$query_2 = array("What is four plus two?", "6");
$query_3 = array("What is seven plus one?", "8");
$query_4 = array("What is six plus three?", "9");

$rand_key = rand(1,4);
$current_query = ('$query_'.$rand_key);
$question = $current_query[0];

print $question;
?>

$ question仅打印“ $”而不是数组的第一个元素。如何获得$ question以打印数组的第一个元素?

-是的,我是php新手。

参考方案

这可能是完成任务的更直接的方法。与其将每个问题存储在自己的数组中并动态获取(即'question' . $random_value),不如将每个问题和答案存储在同一数组中并利用array_rand()

<?php
$questions[] = array("What is two plus three?", "5");
$questions[] = array("What is four plus two?", "6");
$questions[] = array("What is seven plus one?", "8");
$questions[] = array("What is six plus three?", "9");

$randomKey = array_rand($questions); // Returns a random key from $questions
$question = $questions[$randomKey];

print $question[0]; // Question
print $question[1]; // Answer

array_udiff返回不同的结果 - php

我有这段代码来获取两个对象数组之间的区别:$diff = array_udiff($a, $b, function($obj_a, $obj_b) { return $obj_a->id - $obj_b->id; } ); $ a是[ { "id": "7", "attribute":…

PHP-将日期插入日期时间字段 - php

我已在数据库中使用datetime字段存储日期,使用PHP将“今天的日期”插入该字段的正确方法是什么?干杯, 参考方案 我认为您可以使用php date()函数

PHP Count数组元素 - php

嗨,有人可以解释为什么这会返回“数组由0个元素组成”。 :$arr = array(1,3,5); $count = count($arr); if ($count = 0) { echo "An array is empty."; } else { echo "An array has $count elements.…

PHP:从函数返回值并直接回显它? - php

这可能是一个愚蠢的问题,但是……的PHPfunction get_info() { $something = "test"; return $something; } html<div class="test"><?php echo get_info(); ?></div> 有没有办…

PHP:将数据从二维数组复制到一维数组的最快方法 - php

我有一个巨大的二维PHP数组,带有500万行。$t = [ [ "id" => 1, "name" => "foo" ], [ "id" => 2, "name" => "bar" ] ]; 现在,我必须将此数组的I…