如何将变量的值绑定到 php 中的另一个变量

how to bind the value of a variable to another variable in php

我有 3 个数组:

$q1 = ['A', 'B', 'C', 'D'];
$q2 = ['E', 'F', 'G', 'H'];
$q3 = ['I', J', 'K', 'L'];

当我点击表单中的提交时,我存储了一个会话,每次我点击 next,会话将增加 1

session_start();
if(!isset($_SESSION['i']))  {
    $_SESSION['i'] = 0;
}
if(isset($_POST['next'])){
    $_SESSION['i']++;       
}

$session = $_SESSION['i'];
echo $session;

现在我想将会话的值绑定到变量$q

所以1次提交后,$q必须变成$q1,第二次提交后; $q 必须变成 $q2 等等...

所以每次提交时,session的值必须绑定到$q,这样我才能读取不同的数组。

(我想用它来创建动态表单:)

foreach ($q as $key => $value) {
...

我该怎么做?

代替变量 - 使用数组:

// I use explicit indexing, as you start with `i = 1`
$q = [
    1 => ['A', 'B', 'C', 'D'],
    2 => ['E', 'F', 'G', 'H'],
    3 => ['I', 'J', 'K', 'L'],
];

$_SESSION['i'] = 3;
print_r($q[$_SESSSION['i']]);

您的代码看起来不错,快完成了。

所以我使用了另一个 array,它存储了所有其他 arrays

如果您现在获得 $session 变量,您可以访问包装器数组并获得您想要的特定数组。当您以 1 开始数组名称,但以起始索引 1 调用数组时,您必须减去 - 1.

$q1 = array('A', 'B', 'C', 'D');
$q2 = array('E', 'F', 'G', 'H');
$q3 = array('I', 'J', 'K', 'L');

$wrapper = array($q1, $q2, $q3);

$session = 2;

foreach ($wrapper[$session-1] as $key) {
 //Will output E, F , G H as session is =2
 echo $key;

}

Recommended

您可以使用 PHP 数组来执行此操作。

$arr = [
    1 => ['A', 'B', 'C', 'D'],
    2 => ['E', 'F', 'G', 'H'],
    3 => ['I', J', 'K', 'L'],
];

然后,像这样访问它:


print_r($arr[$_SESSION['i']]);

还没准备好使用Arrays?好吧,PHP也允许你使用动态变量名,叫做Variable variables.

$variableName = "q";
//..... Update the value of i in session.

 $variableName .= $_SESSION['i'];// when i = 1, it becomes q1;

 print_r($$variableName); // notice the $$ in the Variable Name
 // output
 // Array (0 => 'A', 1 => 'B', 2 => 'C', 3 => 'D')

Read more about Variable Variables here https://www.php.net/manual/en/language.variables.variable.php