繁体   English   中英

如何通过表单提交传递数组值?

[英]How Can I Pass Array Values through Form Submission?

我正在尝试通过表单提交传递一组值。 举个例子:

example.com?value1=178&value2=345&value3=2356

对于我来说,简单的解决方案是执行以下操作以在新页面上获取值:

$value1=$_GET['value1'];
$value2=$_GET['value2'];
$value3=$_GET['value3'];

我遇到的困难是,每次提交时,通过表格传递的“值”一词后的变量都会改变。 因此,我将代码修改为:

example.com?value14=178&variable=14&value23=345&variable=23&value63=2356&variable=63

如您在这里看到的,我现在将值的传入变量作为GET参数传递。 然后,我尝试获取这些值以分别显示在提交的页面上,如下所示:

$variable=$_GET['variable'];    
$value=$_GET['value'.$variable];

echo $value . '<br>';

此代码几乎可以正常工作。 我能够获得传递给显示的最后一个数组。 如何解决此代码,以使所有传递的值显示在提交的页面上?

对表单字段使用PHP的数组符号:

val[]=178&val[]=14&val[]=345&etc...

这将导致$ _GET ['val']为数组:

$_GET = array(
   'val' => array(178, 14, 345, etc...)
)

如果您无法像这样重新排列网址,则可以尝试使用preg_grep:

$matches = preg_grep('/^variable\d+$/', array_keys($_GET));

这将返回:

$matches= array('variable1', 'variable2', 'variable3', etc...);

例如使用这样的数组,而不需要变量$ variable。

example.com?value[14]=178&value[23]=345&value[63]=2356

foreach ($_GET['value'] as $key => value) {
    echo $key . " => " . $value . "<br/>";
}

编辑:获取值的另一种方法是循环整个$ _GET -array并从那里像这样解析值(变量总是以“值”的形式,后跟X个数字):

example.com?value14=178&value23=345&value63=2356

$values = array();
foreach ($_GET as $key => $value) {
    if (preg_match('/^value[\d]+$/', $key)) {
        // remove "value" from the beginning of the key
        $key = str_replace('value', '', $key);
        // save result to array
        $values[$key] = $value;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM