我想在隱藏字段中發佈數組,並希望在php中提交表單後檢索該數組。使用Html表單隱藏元素傳遞數組
$postvalue=array("a","b","c");
<input type="hidden" name="result" value="<?php echo $postvalue; ?>">
但是在打印發布的值後只獲取數組字符串。 那麼我該如何解決它?
我想在隱藏字段中發佈數組,並希望在php中提交表單後檢索該數組。使用Html表單隱藏元素傳遞數組
$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']);
,你可以做這樣的
<input type="hidden" name="result" value="<?php foreach($postvalue as $value) echo $postvalue.","; ?>">
或者只是使用implode ;-) – Alex
,最好先編碼爲JSON字符串,然後使用Base64編碼如。在服務器端以相反的順序:先使用base64_decode然後使用json_decode函數。所以你會恢復你的PHP陣列
如果你想發表你必須用另一個符號的數組:
foreach ($postvalue as $value){
<input type="hidden" name="result[]" value="$value.">
}
這樣你有一個名爲結果[]三個輸入字段,並張貼$_POST['result']
時候會是一個數組
無論是連載:
$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'])
序列化可以搞砸你的引號或括號,並與html混淆..我會使用接受的答案 – zachu
主要有兩種可能的方式來實現這一目標:
序列化在某些方面的數據:
$postvalue = serialize($array); // client side
$array = unserialize($_POST['result']; //server side
然後你就可以用unserialize($postvalue)
上,這是here in the php manuals更多信息反序列化公佈值。
Alternativley您可以使用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()
檢索數組。但請注意,不應該使用字符作爲數組值中出現的分隔符(或者將其轉義),並且不能使用此方法傳輸數組鍵。
使用特殊的命名輸入元素的屬性:
$postvalue = "";
foreach ($array as $v) {
$postvalue .= '<input type="hidden" name="result[]" value="' .$v. '" />';
}
這樣你得到的$_POST['result']
可變整個數組,如果發送的形式。請注意,這不會傳輸數組密鑰。但是,您可以通過使用result[$key]
作爲每個字段的名稱來實現此目的。
每種方法都有自己的優點和缺點。你使用的主要取決於你的數組的大小,因爲你應該嘗試使用所有這些方法發送最少量的數據。
實現此目的的另一種方式是將數組存儲在服務器端會話中,而不是將其發送到客戶端。像這樣,您可以通過$_SESSION
變量訪問數組,並且不必在表單上傳輸任何內容。對於這種看看a basic usage example of sessions on php.net
<input type="hidden" name="item[]" value="[anyvalue]">
讓它成爲在重複的模式,它會在形式作爲數組發佈此元素,並使用
print_r($_POST['item'])
檢索項目
您可以使用客戶端的序列化和base64_encode, 然後使用反序列化和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
需要序列以某種方式。查看serialize和json_encode函數。我建議使用json_encode。 – Gazler