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

如何遍历PHP中json_decode返回的Notion API复杂关联数组提取指定值

解决方法

单条目标数据直接取值

你已经过滤得到匹配DataElement = bigHouse的条目后,可按照嵌套数组的层级直接读取目标值,对应你给出的数组结构,取值代码如下:

// 替换下标0为你过滤后得到的目标条目实际下标
$targetMeaning = $decoded['results'][0]['properties']['Meaning']['rich_text'][0]['plain_text'];
echo $targetMeaning;

对应层级说明:

  • 所有Notion返回的页面数据都存储在最外层的results数组中
  • 单条页面的字段值都存储在properties字段下,直接用Notion列名作为键即可读取对应字段
  • 富文本/标题类字段的内容分别存储在rich_text/title数组中,单段文本取下标0即可
  • plain_text字段为纯文本内容,已自动忽略格式标记,比读取text.content更稳妥

批量遍历所有结果取值

如果需要遍历所有返回结果过滤并取值,可使用嵌套遍历逻辑:

foreach ($decoded['results'] as $pageItem) {
    // 保留你原有的DataElement过滤逻辑
    $dataElementVal = $pageItem['properties']['DataElement']['title'][0]['plain_text'];
    if ($dataElementVal !== 'bigHouse') {
        continue;
    }
    // 读取Meaning字段值
    $meaningVal = $pageItem['properties']['Meaning']['rich_text'][0]['plain_text'] ?? '';
    echo $meaningVal . '<br>';
}

通用文本字段读取工具函数

如果字段可能包含多段文本,可使用下面的通用方法拼接所有内容,避免漏读:

function getNotionText($field) {
    $content = '';
    $textList = $field['type'] === 'title' ? $field['title'] : $field['rich_text'];
    foreach ($textList as $item) {
        $content .= $item['plain_text'];
    }
    return $content;
}

// 调用示例
$meaning = getNotionText($pageItem['properties']['Meaning']);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 15:24:05