表单_POST数组问题

时间:2009-05-28 22:41:19

标签: php

我有以下代码:

if ( (isset($_GET['slAction'])) && ($_GET['slAction'] == "manage_label") )
{    
  $formData = getFormData();
  foreach ($formData as $key => $value)
    echo "(Key: $key, Value: $value )<br /> ";

}

// All form fields are identified by '[id]_[name]', where 'id' is the 
// identifier of the form type. Eg. label, store etc.
// The field identifier we want to return is just the name and not the id.  
  function getFormData()
  {
    $form_fields = array_keys($_POST); 

    for ($i = 0; $i < sizeof($form_fields); $i++) 
    {
      $thisField = $form_fields[$i];
      $thisValue = $_POST[$thisField];

      //If field is an array, put all it's values into one string 
      if (is_array($thisValue))
      {
        for ($j = 0; $j < sizeof($thisValue); $j++)
        {
          $str .= "$thisValue[$j],";
        }

        // Remove the extra ',' at the end
        $thisValue =  substr($str, 0, -1);

       //Assosiative array $variable[key] = value
       $formData[end(explode("_", $thisField))] = $thisValue;
      }
      else 
        $formData[end(explode("_", $thisField))] = $thisValue;      
    } 
    return $formData;
  }

此代码的输出为:

(Key: id, Value: 7276 )
(Key: name, Value: 911 Main brand )
(Key: email, Value: )
(Key: www, Value: )
(Key: categories, Value: Menswear,Womenswear,Shoes )
(Key: targetgroup, Value: )
(Key: keywords, Value: )
(Key: description, Value: Testing )
(Key: saveForm, Value: Save )

现在这是我的问题。名为“label_categories”的表单字段是复选框,并作为数组返回。如你所见,输出是“男装,女装,鞋子”。 如果我尝试'echo $ formData ['name']',则输出为“911 Main brand”。 如果我尝试'echo $ formData ['categories']。输出为空白/空。

为什么我可以输出字符串'name'而不是字符串'categories'?在getFormData()函数中,我将数组转换为字符串....

任何帮助表示感谢。

2 个答案:

答案 0 :(得分:1)

该代码可以极大简化:

// 1. no need for isset() check in the case where you're testing a value
// 2. use single quotes for strings where possible
if ($_GET['slAction'] == 'manage_label') {    
  $formData = getFormData();
  // 3. Good rule is to use braces even when not necessary
  foreach ($formData as $key => $value) {
    echo "(Key: $key, Value: $value )<br /> ";
  }
}

function getFormData() {
  // 4. prefer explicit initialization
  $formData = array();
  // 5. this foreach is much cleaner than a loop over keys
  foreach ($_POST as $k => $v) {
    // 6. this is a lot cleaner than end(explode(...))
    $name = preg_replace('!.*_!', '', $k);
    if (is_array($v)) {
      // 7. this implode() replaces 5 lines of code
      // and is MUCH clearer to read
      $formData[$name] = implode(',', $v);
    } else {
      $formData[$name] = $v;
    }
  }
  return $formData;
}

答案 1 :(得分:0)

而不是发布代码,生病解释。

你不能回应$ _post ['catagories'],因为它不是字符串或数字。这是一个数组。

你可以回复$ _post ['catagories'] [nth number']或echo implode(','$ _post ['catagories'])