php, html generate form from mutiple variables
I need to generate a html form with different hidden variables . However the "problem" is that there are a lot of variables .e.g
$siteId = getValue("siteId", $localurl); $itemid = getValue("itemid", $localurl); $bidqty = getValue("bidqty", $localurl); $maxbid = getValue("maxbid", $localurl); $lagoonemorebid = getValue("lagoonemorebid", $localurl);... the above vars are just a few from the whole list . Basically I can generate the form manually with$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("buye开发者_如何学JAVArLogging", $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\" />but I was wondering if there is a "smart" technique to use foreach or some function to get all the variables and generate the form instead to write manually all the hidden inputs ...
Yes there is a way. Add all your values into an array and use the PHP function array_walk.
eg:
$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' );
The advantage of this method is that your array $hiddenVars could change dynamically and this would still work.
I will assume getValue is a custom function. My recommendation would be the following:
<?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, '" />';
}
?>
You could do this with a single array, but I feel this is more flexible.
Well there is a smarter way. You can use just one hidden field and the value would be encoded serialized string of all of your variables :
$options = array(
'asd' => 1,
'zxc' => 2,
);
$options = base64_encode(serialize($options));
echo '<input type="hidden" name="state" value="' . $options . '" />';
Then you can get values like this:
$options = unserialize(base64_decode($_POST['state']));
精彩评论