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

如何通过嵌套循环生成指定结构的数组?WordPress开发求助

问题:WordPress生成城市对应房产ID数组时,所有城市property数据重复

期望生成如下结构的数组,每个城市对应专属的房产ID列表:

{"status": 200,
"data": [
    {
        "city": "City 1",
        "property": [
            {
                "id": 1
            },
            {
                "id": 2
            }
        ]
    },
    {
        "city": "City 2",
        "property": [
            {
                "id": 3
            },
            {
                "id": 2
            }
        ]
    },
    {
        "city": "City 3",
        "property": [
            {
                "id": 18132
            },
            {
                "id": 17981
            }
        ]
    }
]
}

但使用以下WordPress代码生成时,所有property字段始终获取到相同的数据:

$custom_terms = get_terms('property_state');

foreach($custom_terms as $custom_term) {
    wp_reset_query();
    $args = array('post_type' => 'property',
        'tax_query' => array(
            array(
                'taxonomy' => 'property_state',
                'field' => 'slug',
                'terms' => $custom_term->slug,
            ),
        ),
     );

     $loop = new WP_Query($args);
     if($loop->have_posts()) {
        $city_name = $custom_term->name;
        while($loop->have_posts()) : $loop->the_post();
            $property[] =  array(
               'id' => get_the_ID(),
             );
        endwhile;
     }
        $final[] = array('city'=>$city_name, 'property' => $property);
}

错误原因

问题出在$property数组未在每次循环城市时重置。当前代码中$property是全局累加状态,每遍历一个新城市,该城市的房产ID会追加到之前的$property数组中,导致后续城市的property字段包含前面所有城市的房产ID,最终所有城市的property数据完全重复。


修正后的代码

在每次遍历城市的循环内初始化$property为空数组,确保每个城市的房产ID单独收集:

$custom_terms = get_terms('property_state');
$final = array(); // 初始化最终数组,避免未定义警告

foreach($custom_terms as $custom_term) {
    wp_reset_query();
    $property = array(); // 关键:每次循环城市时重置property数组
    $args = array(
        'post_type' => 'property',
        'tax_query' => array(
            array(
                'taxonomy' => 'property_state',
                'field' => 'slug',
                'terms' => $custom_term->slug,
            ),
        ),
    );

    $loop = new WP_Query($args);
    if($loop->have_posts()) {
        $city_name = $custom_term->name;
        while($loop->have_posts()) : $loop->the_post();
            $property[] = array(
                'id' => get_the_ID(),
            );
        endwhile;
    }
    $final[] = array('city' => $city_name, 'property' => $property);
}

// 按需求包装成指定的JSON结构
$result = array(
    'status' => 200,
    'data' => $final
);
echo json_encode($result);

内容的提问来源于stack exchange,提问作者zeba puthawala

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 03:10:16