如何从PHP的POST请求参数中生成指定结构的多维关联数组?
实现方案
你当前的表单提交后,PHP会自动将name带[]的参数解析为索引数组,$_POST['location']、$_POST['msg']、$_POST['order_id']三个数组的下标完全对应你渲染时的$i值,直接遍历组装即可得到目标结构:
后端处理代码
// 初始化结果数组 $targetArr = []; // 校验必填参数是否存在 if (isset($_POST['location'], $_POST['msg'], $_POST['order_id'])) { // 校验三个数组长度一致,避免异常 $count = count($_POST['location']); if ($count === count($_POST['msg']) && $count === count($_POST['order_id'])) { for ($i = 0; $i < $count; $i++) { // 可按需增加空值过滤逻辑,跳过无效项 $location = $_POST['location'][$i]; $msg = $_POST['msg'][$i]; $orderId = $_POST['order_id'][$i]; // 按要求组装数组,相同location会覆盖旧值,如需保留可改为 $targetArr[$location][] = [$msg => $orderId] $targetArr[$location] = [ $msg => $orderId ]; } } } // 打印验证结果 var_dump($targetArr);
可选优化:表单结构调整(简化后端逻辑)
如果你不需要单独获取三个字段的独立数组,可以直接将表单的name属性改为分组格式,提交后PHP会自动生成二维索引数组,后续组装逻辑更清晰:
// 渲染表单时代码调整 $html .= '<td><input name="items['.$i.'][location]" type="text" class="form-control form-control-sm form-control-solid" placeholder="result data (kosongkan jika tidak diperlukan)" value=""/></td>'; $html .= '<td><input name="items['.$i.'][msg]" type="text" class="form-control form-control-sm form-control-solid" value="' . htmlspecialchars($key) . '"/></td>'; $html .= '<td><input name="items['.$i.'][order_id]" type="text" class="form-control form-control-sm form-control-solid" value="' . htmlspecialchars($value) . '"/></td>';
提交后$_POST['items']会自动生成如下结构:
[ 0 => ['location' => 'xxx', 'msg' => 'yyy', 'order_id' => 'zzz'], 1 => ['location' => 'aaa', 'msg' => 'bbb', 'order_id' => 'ccc'], // ...其他项 ]
后续遍历组装目标结构的逻辑更易维护。
内容的提问来源于stack exchange,提问作者Tech
相关产品推荐
相关产品推荐

