WP-JSON REST API导出移动端适配数据格式问题求助
修正WP-JSON REST API的事件分组格式问题
我明白你现在的核心问题——当前代码每循环一个事件就往schedule里塞一个独立的日期条目,完全没做同日期合并、同时间分组的逻辑,所以才会出现每个事件都是单独schedule元素的情况。咱们来修改代码,实现你要的层级结构:
问题根源分析
你原来的代码在while循环里,每次都新建一个['date' => ..., 'groups' => [...]]对象并推入schedule数组,相当于把每个事件都当成了独立的日期分组,完全没有合并同日期、同时间的事件。
修正后的代码
function app_get_newer_posts($data) { $args = array( 'post_type' => 'event', 'post_status' => 'publish', 'posts_per_page' => 8, 'paged' => $data['page'] ); $query = new WP_Query( $args ); $ret = ['schedule' => []]; // 临时数组:用日期字符串做键,方便快速分组 $temp_schedule = []; if ($query->have_posts()) { setlocale(LC_TIME, 'ita', 'it_IT'); while ( $query->have_posts() ) { $query->the_post(); $post_id = get_the_ID(); // 获取事件开始时间戳(用true直接返回单个值,避免数组索引) $start_timestamp = get_post_meta($post_id, 'ovaem_date_start_time', true); // 跳过已过期的事件(保留你原来的逻辑) if ($start_timestamp < date("Y-m-d")) { continue; } // 格式化需要的日期、时间字符串 $date_str = date('Y-m-d', $start_timestamp); $time_str = utf8_encode(strftime("%d %b %Y", $start_timestamp)); // 组装单条session数据,增加空值容错 $session = [ 'name' => html_entity_decode(get_the_title(), ENT_QUOTES), 'location' => get_the_terms($post_id, 'location')[0]->name ?? '未设置地点', 'description' => get_the_content(), 'timeStart' => date('d M Y h:i', $start_timestamp), 'timeEnd' => date('d M Y h:i', get_post_meta($post_id, 'ovaem_date_end_time', true)), 'tracks' => [ get_the_terms($post_id, 'categorie')[0]->name ?? '未分类' ], 'id' => $post_id, 'pic' => get_the_post_thumbnail_url() ?? '' ]; // 第一步:按日期分组,日期不存在则初始化结构 if (!isset($temp_schedule[$date_str])) { $temp_schedule[$date_str] = [ 'date' => $date_str, 'groups' => [] ]; } // 第二步:在当前日期下,查找是否已有对应时间的group $target_group_index = -1; foreach ($temp_schedule[$date_str]['groups'] as $index => $group) { if ($group['time'] === $time_str) { $target_group_index = $index; break; } } // 如果没有该时间的group,新建一个 if ($target_group_index === -1) { $temp_schedule[$date_str]['groups'][] = [ 'time' => $time_str, 'sessions' => [] ]; $target_group_index = count($temp_schedule[$date_str]['groups']) - 1; } // 第三步:把当前session加入对应group的sessions数组 $temp_schedule[$date_str]['groups'][$target_group_index]['sessions'][] = $session; } // 把临时数组的结构转换为预期的数组格式(去掉键,保留值列表) $ret['schedule'] = array_values($temp_schedule); } // 重置WP查询上下文,避免影响后续操作 wp_reset_postdata(); // 以WP REST API规范的格式返回数据 return rest_ensure_response($ret); }
关键改动说明
- 新增临时分组数组:用
$temp_schedule按日期字符串做键,快速定位同日期的分组,避免重复创建date条目 - 双层分组逻辑:先按日期归类,再在日期下按时间分组,确保同时间的事件都进同一个
sessions数组 - 增加容错处理:用
??运算符处理分类/地点未设置的情况,避免PHP报错 - 规范REST响应:加上
wp_reset_postdata()和rest_ensure_response(),符合WordPress REST API的开发规范 - 优化元数据获取:用
get_post_meta(..., true)直接返回单个值,不用数组索引[0]更安全
这样修改后,返回的数据结构就会和你预期的一致:事件按日期分组,每个日期下按时间分成不同的group,每个group下的sessions包含该时间的所有事件。
内容的提问来源于stack exchange,提问作者andreyo
相关产品推荐
相关产品推荐

