使用HTML表单隐藏元素传递数组


Passing an array using an HTML form hidden element

我正试图在隐藏字段中发布一个数组,并希望在用PHP提交表单后检索该数组。

$postvalue = array("a", "b", "c");
<input type="hidden" name="result" value="<?php echo $postvalue; ?>">

但是在打印发布的值之后,我只得到一个数组字符串。那么我该如何解决呢?

使用:

$postvalue = array("a", "b", "c");
foreach($postvalue as $value)
{
    echo '<input type="hidden" name="result[]" value="'. $value. '">';
}

您将得到$_POST['result']作为一个数组。

print_r($_POST['result']);

实现这一点主要有两种可能的方法:

  1. 以某种方式序列化数据:

    $postvalue = serialize($array); // Client side
    $array = unserialize($_POST['result']; // Server side
    

然后可以使用unserialize($postvalue)取消对发布的值的序列化。有关这方面的更多信息,请参阅PHP手册。

或者,您可以使用json_encode()json_decode()函数来获得JSON格式的序列化字符串。您甚至可以使用gzcompress()收缩传输的数据(请注意,这是性能密集型的(,并使用base64_encode()保护传输数据(使您的数据在非8位干净传输层中生存(

    $postvalue = base64_encode(json_encode($array)); // Client side
    $array = json_decode(base64_decode($_POST['result'])); // Server side

不推荐串行化数据的方法(但性能非常便宜(是简单地在数组上使用implode()来获得一个字符串,其中所有值都由某个指定字符分隔。在服务器端,您可以使用explode()检索数组。但请注意,不应使用字符来分隔数组值中出现的分隔(或转义它(,并且不能使用此方法传输数组键。

  1. 使用特殊命名输入元素的属性:

    $postvalue = "";
    foreach ($array as $v) {
      $postvalue .= '<input type="hidden" name="result[]" value="' .$v. '" />';
    }
    

    像这样,如果发送了表单,则可以在$_POST['result']变量中获得整个数组。请注意,这不会传输数组密钥。但是,您可以通过使用result[$key]作为每个字段的名称来实现这一点。

这些方法每个人都有自己的优点和缺点。使用什么主要取决于数组的大小,因为您应该尝试使用所有这些方法发送最少的数据量。

实现这一点的另一种方法是将阵列存储在服务器端会话中,而不是在客户端进行传输。像这样,你可以通过$_SESSION变量访问数组,而不必通过表单传输任何内容

您可以从客户端使用serialize和base64_encode。之后,在服务器端使用unserialize和base64_decode。

类似:

在客户端,使用:

    $postvalue = array("a", "b", "c");
    $postvalue = base64_encode(serialize($array));
   // Your form hidden input
   <input type="hidden" name="result" value="<?php echo $postvalue; ?>">

在服务器端,使用:

    $postvalue = unserialize(base64_decode($_POST['result']));
    print_r($postvalue) // Your desired array data will be printed here

序列化:

$postvalue=array("a","b","c");
<input type="hidden" name="result" value="<?php echo serialize($postvalue); ?>">

接收时:unserialize($_POST['result'])

或内爆:

$postvalue=array("a","b","c");
<input type="hidden" name="result" value="<?php echo implode(',', $postvalue); ?>">

接收时:explode(',', $_POST['result'])

如果要发布数组,必须使用另一种表示法:

foreach ($postvalue as $value){
<input type="hidden" name="result[]" value="$value.">
}

通过这种方式,您有三个名称为result[]的输入字段,当发布$_POST['result']时,它将是一个数组

<input type="hidden" name="item[]" value="[anyvalue]">

如果它处于重复模式,它将以数组的形式发布此元素,并使用

print_r($_POST['item'])

检索项目

最好先将其编码为JSON字符串,然后使用Base64进行编码,例如,在服务器端按相反的顺序进行编码:首先使用Base64_decode,然后使用JSON_decode函数。因此,您将恢复您的PHP数组。

你可以这样做:

<input type="hidden" name="result" value="<?php foreach($postvalue as $value) echo $postvalue.","; ?>">