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

时间:2012-03-27 14:53:13

标签: 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只需打印&#34; $&#34;而不是数组的第一个元素。如何获得$ question来打印数组的第一个元素?

- 是的,我是一个php noob。

6 个答案:

答案 0 :(得分:5)

这可能是一种更直接的完成任务的方式。不是将每个问题存储在自己的数组中并动态获取(即'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

答案 1 :(得分:3)

修复您的来源:

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

print $question;

答案 2 :(得分:1)

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

$rand = rand(0,count($qa)-1);

print $qa[$rand][0];
?>

答案 3 :(得分:0)

尝试使用括号。

$question = "{$current_query[0]}";

答案 4 :(得分:0)

使用您当前的数据结构,您需要使用Variable variables ...

$current_query = 'query_'.$rand_key;  // Removed $ prefix in front of 'query'
$question = ${$current_query}[0]      // Variable variables

变量的名称存储在$current_query中,通过在此前面放置另一个$,您将访问存储在该名称变量中的值。花括号(复杂的语法)避免任何歧义,即。您不是指存储在数组的第一个元素中的变量的名称。

但是,有更好的方法来存储您的数据,例如@Mike B

建议

答案 5 :(得分:0)

尝试:

eval("\$question = ".$current_query."[0];");

参考:http://php.net/manual/en/function.eval.php

相关问题