将经典的asp函数转换为php:循环遍历request.form

将经典的asp函数转换为php:循环遍历request.form

问题描述:

I'm fairly new to php. I'm trying to translate a classic asp vbscript function to php. It's looping through the request.form values and generating a string. I found this article about looping through $_REQUEST.

This is the vb function:

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:

$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. 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).

$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