将复杂数组转换为foreach循环

时间:2013-05-28 23:48:43

标签: php mysql arrays

我有一个应用程序,其中有2个初始字段:

  1. 名称
  2. 价格
  3. 表单如下所示:

    <form>
    <input type="hidden" name="type" value="television" />
    <label>Name <input type="text" name="name[]" /></label>
    <label>Price <input type="text"" name="price[]" /></label>
    </form>
    

    目前,用户可以向表单“添加更多”字段,这样可以正常工作。因此,例如,如果有人点击添加更多按钮,则表单如下所示:

    <form>
    <input type="hidden" name="type" value="television" />
    
    <label>Name <input type="text" name="name[]" /></label>
    <label>Price <input type="text"" name="price[]" /></label>
    
    <label>Name <input type="text" name="name[]" /></label>
    <label>Price <input type="text"" name="price[]" /></label>
    </form>
    

    然后他们可以添加更多名称/价格。我遇到的问题是我无法将第一个价格字段与第一个名字字段相关联,依此类推,因此当我要将其插入数据库时​​,第四个。我正在使用ajax发布数据,而且工作正常。

    目前,当var_dump帖子时,数组看起来像这样:

    array(3) {
      ["type"]=>
      string(10) "television"
      ["name"]=>
      array(2) {
        [0]=>
        string(8) "name one"
        [1]=>
        string(8) "name two"
      }
      ["price"]=>
      array(2) {
        [0]=>
        string(9) "price one"
        [1]=>
        string(9) "price two"
      }
    }
    

    我需要的是能够将数组值合并为完全如下:

    array(
        "name" => "name one",
        "price" => "price one",
        "type" => "television"
    )
    
    array(
        "name" => "name two",
        "price" => "price two",
        "type" => "television"
    )
    

    非常感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

如果您知道每个name将有price,那么您可以使用key中任意一个的$_POST array variables来创建输出。

注意:这不会创建单独的数组,但会将三者组合在一起以便于“可读性”:

$_POST = array(
  "type"=> "television",
  "name"=> array("name one","name two"),
  "price"=> array("price one","price two"),
);

$output = array();
foreach($_POST['name'] as $key=>$name){
    $output[$key]['name'] = $name;
    $output[$key]['price'] = $_POST['price'][$key];
    $output[$key]['type'] = $_POST['type'];
}
echo '<pre>',print_r($output),'</pre>';