猿问

如何正确重新排序来自 HTML 的 POST 数组?

考虑到我有一个这样的数组:


array:3 [▼

  "description" => array:2 [▼

    0 => "serv1"

    1 => "serv2"

  ]

  "quantity" => array:2 [▼

    0 => "1"

    1 => "2"

  ]

  "cost" => array:2 [▼

    0 => "100"

    1 => "200"

  ]

]

来自如下所示的 HTML 表单:


<div class="col-md-6">

    <div class="form-group">

        <input 

            type="text" 

            name="service[description][]" 

            class="form-control" 

        />

    </div>

</div>

<div class="col-md-3">

    <div class="form-group">

        <input 

            type="text" 

            name="service[quantity][]" 

            class="form-control"

        />

    </div>

</div>

<div class="col-md-3">

    <div class="form-group">

        <input 

            type="text" 

            name="service[cost][]" 

            class="form-control" 

        />

    </div>

</div>

我怎样才能以这样的方式修复数组,结果是这样的:


[

    ["description" => "serv1", "quantity" => "1", "cost" => "100"],

    ["description" => "serv2", "quantity" => "2", "cost" => "200"],

]


慕码人8056858
浏览 107回答 2
2回答

慕桂英546537

循环数组第一个子数组并使用array_column。使用 array_combine 和 array_keys 使密钥正确。foreach($_POST["description"] as $key => $val){&nbsp; &nbsp; $new[] = array_combine(array_keys($_POST),array_column($_POST, $key));}

UYOU

如果这是一个选项 - 将您的标记重建为:<div class="col-md-6">&nbsp; &nbsp; <div class="form-group">&nbsp; &nbsp; &nbsp; &nbsp; <input&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type="text"&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; name="service[0][description]"&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; class="form-control"&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; </div></div><div class="col-md-3">&nbsp; &nbsp; <div class="form-group">&nbsp; &nbsp; &nbsp; &nbsp; <input&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type="text"&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; name="service[0][quantity]"&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; class="form-control"&nbsp; &nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; </div></div><div class="col-md-3">&nbsp; &nbsp; <div class="form-group">&nbsp; &nbsp; &nbsp; &nbsp; <input&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type="text"&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; name="service[0][cost]"&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; class="form-control"&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; </div></div>注意属性中的显式索引name。使用inputs 的这种命名,您的 POST 数组将已经按照您的需要构建,并且不需要服务器端重建。
随时随地看视频慕课网APP
我要回答