[英]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.