You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

存储到数据库前重构WordPress嵌套Repeater的多维$_POST数组

WordPress中ACF嵌套Repeater前端提交表单的多维POST数组重构问题

我在WordPress中使用ACF构建了一个包含嵌套Repeater的前端提交表单:主Repeater字段为Spaces(空间),嵌套Repeater字段为Walls(墙体)。用户可添加多个空间,每个空间又可添加多个墙体。

初始实现:仅处理主Repeater

前端输入字段结构如下:

<input type="text" name="spaces[1][space]">
<input type="text" name="spaces[2][space]">

通过AJAX提交后,PHP处理代码可正常将数据存入数据库:

if(isset($_POST['spaces'])) {
    $spaces = array();
    foreach ($_POST['spaces'] as $value) {
        $spaces[] = array(
            "space" => $value['space'],
        );
    }
}

加入嵌套Repeater后的静态实现

添加墙体字段后,前端输入字段变为:

<input type="text" name="spaces[1][walls][1][orientation]">
<input type="text" name="spaces[1][walls][2][orientation]">

静态示例代码可正常存储数据,但无法适配用户动态添加的任意数量墙体,需要修改PHP代码以正确通过$_POST获取值。AJAX提交代码如下:

var formData = form.serialize();
$.ajax({ type: 'POST', url: ajaxurl, data: formData });

迭代优化过程

更新1:可运行但不规范的代码

编写了以下代码可实现功能,但代码不够规范:

if(isset($_POST['spaces'])) {
    $spaces = array();
    foreach ($_POST['spaces'] as $value) {
        if($value['walls']) {
            $walls_array = array();
            foreach ($value['walls'] as $wall) {
                $walls_array[] = array( "orientation" => $wall['orientation'] );
            }
        } else {
            $walls_array = '';
        }
        $spaces[] = array(
            "space"             => $value['space'],
            "walls"             => $walls_array,
            "extra_information" => $value['extra_information'],
        );
    }
}

更新2:优化后的规范代码

参考@mickmackusa的答案优化后的代码运行良好:

$spaces = array_map(
    fn($space) => [
        "space"             => $space['space'],
        "walls"             => array_map(
                                fn($wall) => [
                                    "orientation" => $wall['orientation'],
                                    "comments" => $wall['comments']
                                ], $space['walls']),
        "extra_information" => $space['extra_information'],
    ],
    $_POST['spaces'] ?? []
);

当前问题:动态索引下的多维数组重构

由于用户可添加和排序空间与墙体,手动维护HTML输入字段的索引非常困难,因此希望改用无指定索引的命名格式:

<input type="text" name="spaces[][walls][][orientation]">
<input type="text" name="spaces[][walls][][orientation]">

参考代码在无墙体时可正常运行,但添加墙体后会产生空的空间和墙体数据,导致存入数据库异常:

$spaces_temp = [];
foreach($_POST['spaces'] as $k=>$v){
    $val = intdiv($k,2);
    $spaces_temp[$val][key($v)]=$v[key($v)];
}
$_POST['spaces']=$spaces_temp;

现寻求该动态索引下多维$_POST数组的正确重构方法,确保数据准确存入数据库。


内容的提问来源于stack exchange,提问作者Senne Vandenputte

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 19:47:57