我需要生成一个包含不同隐藏变量的html表单。然而,“问题”是存在很多变量.e.g
$siteId = getValue("siteId", $localurl); $itemid = getValue("itemid", $localurl); $bidqty = getValue("bidqty", $localurl); $maxbid = getValue("maxbid", $localurl); $lagoonemorebid = getValue("lagoonemorebid", $localurl);......上述变量只是整个列表中的一些变量。基本上我可以使用$tokenstring = getValue("tokenstring", $localurl); $usage = getValue("usage", $localurl); $robotimage = getValue("robotimage", $localurl); $ru = getValue("ru", $localurl); $usergoal = getValue("usergoal", $localurl); $reporting = getValue("reporting", $localurl); $buyerLogging = getValue("buyerLogging", $localurl); $runame = getValue("runame", $localurl); $ruparams = getValue("ruparams", $localurl); $PromoCode = getValue("PromoCode", $localurl);
echo " form action=\"http://$domain/mailer/create.php\" name=\"create\" method=\"post\" /> input type=\"hidden\" name=\"random\" value=\"$random\" />手动生成表单 但我想知道是否有一种“智能”技术使用foreach或某些函数来获取所有变量并生成表单而不是手动编写所有隐藏的输入...
答案 0 :(得分:1)
是的,有办法。将所有值添加到数组中并使用PHP函数 array_walk 。
例如:
$hiddenVars = array(
'siteId' => getValue("siteId", $localurl),
'itemid' => getValue("itemid", $localurl),
.....
);
function outputHiddenFields(&$val, $key) {
echo '<input type="hidden" name="', $key, '" value="', $val, '" />';
}
array_walk( $hiddenVars, 'outputHiddenFields' );
这种方法的优点是你的数组$ hiddenVars可以动态改变,这仍然有用。
答案 1 :(得分:0)
我假设getValue是一个自定义函数。我的建议如下:
<?php
// arrays to facilitate foreach loop
$hidden_fields = array('siteId', 'itemid', 'bidqty'); // store hidden field names
$hidden_values = array(); // store the hidden field values
foreach ($hidden_fields as $key => $value) {
// fill the values array using the values from fields array
$hidden_values[$value] = getValue($value, $localurl);
}
<?php
echo "
form action=\"http://$domain/mailer/create.php\" name=\"create\" method=\"post\" />
input type=\"hidden\" name=\"random\" value=\"$random\" />";
// output hidden fields
foreach ($hidden_values as $key => $value) {
echo '<input type="hidden" name="', $key, '" value="', $value, '" />';
}
?>
您可以使用单个数组执行此操作,但我觉得这更灵活。
答案 2 :(得分:0)
有一种更聪明的方法。您只能使用一个隐藏字段,该值将编码所有变量的序列化字符串:
$options = array(
'asd' => 1,
'zxc' => 2,
);
$options = base64_encode(serialize($options));
echo '<input type="hidden" name="state" value="' . $options . '" />';
然后你可以得到这样的值:
$options = unserialize(base64_decode($_POST['state']));