<分区>
我目前无法访问一个数组,其中数组的名称由 $_GET 定义。
如果我有以下数组:
$test = array('Hello', 'Apples', 'Green');
$AnotherArray = array('Blue', 'Sun');
然后我想显示数组 $test,当我像这样打开我的脚本时:
ajax.php?arrayName=test
提前感谢您的帮助。
<分区>
我目前无法访问一个数组,其中数组的名称由 $_GET 定义。
如果我有以下数组:
$test = array('Hello', 'Apples', 'Green');
$AnotherArray = array('Blue', 'Sun');
然后我想显示数组 $test,当我像这样打开我的脚本时:
ajax.php?arrayName=test
提前感谢您的帮助。
最佳答案
你可以用variable variables完成这个:
$the_array = ${$_GET['arrayName']};
重要
这就像使用炸药一样,因为恶意用户可以轻松地将变量名与其他名称交换并破坏您的应用。
最佳做法是首先将变量名列入白名单:
$safe_vars = array('test', 'AnotherArray');
if (in_array($_GET['arrayName'], $safe_vars, true)) {
$the_array = ${$_GET['arrayName']};
}
备选
作为mentioned通过 Pekka 웃 ,您还可以考虑将可访问数组放在一个母数组中:
$arrays = array(
'test' => array('Hello', 'Apples', 'Green'),
'AnotherArray' = array('Blue', 'Sun')
);
if (isset($arrays[$_GET['arrayName']])) {
$the_array = $arrays[$_GET['arrayName']];
}
这里的好处是没有使用魔法,只是简单的数组解引用。
关于php - 访问 PHP 数组 - $_GET 定义的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16401084/