
本文介绍如何将第三方 api 返回的、按 meta_key 分离存储的 faq 问答项(如 faq_list_0_question 和 faq_list_0_answer)自动配对合并为结构清晰的二维数组,支持任意数量 faq 条目,无需手动干预。
在处理来自不可控第三方 API 的 WordPress 自定义字段(post meta)数据时,FAQ 内容常被拆分为多个独立条目:每个问题与对应答案分别以 xxx_question 和 xxx_answer 形式存在,且共享相同的序号标识(如 _0_、_1_)。原始数据结构扁平、冗余,不利于前端渲染或业务逻辑处理。我们需要将其智能聚合成语义明确的 FAQ 对象集合。
核心思路是基于 meta_key 的命名规律提取唯一分组键(如 "0")和类型("question" / "answer"),再按序号归并。以下是推荐的健壮实现:
<?php
// 假设 $apiResponse 是从 API 获取的完整响应(含 'data' 键)
$newFaqs = [];
foreach ($apiResponse['data'] as $item) {
// 安全校验必要字段
if (!isset($item['meta_key']) || !isset($item['meta_value'])) {
continue;
}
// 拆分 meta_key,例如 "faq_list_0_question" → ['faq', 'list', '0', 'question']
$parts = explode('_', $item['meta_key']);
// 末尾必为类型(question/answer),倒数第二位应为数字索引
$type = array_pop($parts);
$index = array_pop($parts); // 如 '0', '1', '2'
// 验证索引是否为有效非负整数(增强鲁棒性)
if (!is_numeric($index) || (int)$index < 0) {
continue;
}
$index = (string)(int)$index; // 标准化为字符串数字,避免键名不一致
// 初始化该索引的 FAQ 条目(若首次出现)
if (!isset($newFaqs[$index])) {
$newFaqs[$index] = [
'id' => $index,
'question' => '',
'answer' => ''
];
}
// 按类型存入内容(仅取 meta_value,符合常见需求)
if ($type === 'question') {
$newFaqs[$index]['question'] = $item['meta_value'];
} elseif ($type === 'answer') {
$newFaqs[$index]['answer'] = $item['meta_value'];
}
}
// 转为纯索引数组(移除关联键,便于 JSON 序列化或遍历)
$finalFaqs = array_values($newFaqs);
?>✅ 输出示例($finalFaqs):
[
{
"id": "0",
"question": "Lorem ipsum dolor sit amet...",
"answer": "In at neque at nisl fringilla egestas..."
},
{
"id": "1",
"question": "How do I reset my password?",
"answer": "Go to login page and click 'Forgot Password'..."
}
]? 关键优势与注意事项:
立即学习“PHP免费学习笔记(深入)”;
- 容错性强:跳过缺失字段或非法 meta_key 格式的数据,避免脚本中断;
- 索引标准化:强制转换为整型再转字符串,防止 "00"、"0" 等歧义键名;
- 可扩展设计:若需保留原始 id 或 post_id,可轻松扩展 $newFaqs[$index] 结构;
- 性能友好:单次遍历,时间复杂度 O(n),适用于数百条 FAQ 场景;
- 兼容性提示:确保 PHP 版本 ≥ 7.0(array_values() 等函数支持良好)。
最终,你获得的是一个结构规整、语义清晰、可直接用于模板渲染或 API 响应的 FAQ 数组,彻底解耦了原始数据的“扁平化”缺陷。











