[英]Translating classic asp function to php: looping through request.form
I'm fairly new to php. 我是php的新手。 I'm trying to translate a classic asp vbscript function to php.
我正在尝试将经典的ASP vbscript函数转换为php。 It's looping through the
request.form
values and generating a string. 它遍历
request.form
值并生成一个字符串。 I found this article about looping through $_REQUEST
. 我发现这篇关于循环
$_REQUEST
文章 。
This is the vb function: 这是vb函数:
obj = "{"
for each prod in request.Form
if prod <> "checkout" then obj = obj & "'" & prod & "':" & request.Form(prod) & ","
next
obj = left(obj, len(obj)-1) & "}" 'take out last comma
This is typical data in the form post: 这是表单发布中的典型数据:
checkout: true
2012ORGANIC500ML: 1
it generates this string: 它生成以下字符串:
{'2012ORGANIC500ML':1}
My attempt in php is this: 我在php中的尝试是这样的:
$obj = "{";
foreach ($_REQUEST as $prod) {
if ($prod != "checkout") { $obj .= "'" . $prod . "':" . $_REQUEST[$prod] . ","; };
};
$obj .= substr($obj, 0, -1) . "}";
Which returns this erroneous string: 返回错误的字符串:
{'true':,'1':,{'true':,'1':}
Can someone point me in the right direction? 有人可以指出我正确的方向吗? Thanks in advance.
提前致谢。
if you do foreach($_REQUEST as $prod) then you get only the value in your loop, not the key. 如果您执行foreach($ _ REQUEST作为$ prod),那么您只会在循环中获得值,而不是键。 So try this:
所以试试这个:
foreach ($_REQUEST as $key => $val) {
if ($key != "checkout") { $obj .= "'" . $key . "':" . $val . ","; };
};
By the way... if you need your data in json format you can simply do json_encode($data). 顺便说一下...如果您需要json格式的数据,则只需执行json_encode($ data)。
$data = $_REQUEST;
$checkout = $data['checkout']; // get your checkout var
unset($data['checkout']); // remove checkout from data
$obj = json_encode($data); // json encode your data to $obj
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.