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

PHP如何提取JSON文件中单个对象的yes-or-no字段并输出

问题排查

你写的代码报错核心有两个原因:

  • API返回的JSON最外层是数组结构,json_decode后得到的是索引数组,不是直接包含yes-or-no字段的对象
  • PHP中对象属性名如果包含横杠这类特殊字符,不能直接用->属性名访问,需要用大括号包裹属性名:->{'yes-or-no'}

如果要遍历输出所有项的yes-or-no值,修复后的代码如下:

<?php
$status = json_decode(file_get_contents('url to the json file'));
foreach ($status as $item) {
    echo $item->{'yes-or-no'}.'<br />';
}
?>

仅输出单个值的实现

固定取指定位置的项

如果你要取第一个项(对应name为Test 1)的值,直接通过数组索引定位即可,不需要遍历:

<?php
$status = json_decode(file_get_contents('url to the json file'));
// 数组索引从0开始计数,0对应第一个项,1对应第二个项
echo $status[0]->{'yes-or-no'};
?>

如果要取第二个项(name为Test 2)的结果,把索引0改成1即可。

按name字段匹配取值

如果你需要根据name的值匹配对应结果,可以加判断筛选:

<?php
$status = json_decode(file_get_contents('url to the json file'));
$targetName = 'Test 1'; // 替换成你要匹配的name值
foreach ($status as $item) {
    if ($item->name === $targetName) {
        echo $item->{'yes-or-no'};
        break; // 匹配到结果后直接退出循环,减少性能消耗
    }
}
?>

小提示:

  1. 你提供的JSON示例里每个对象的name和yes-or-no字段之间缺少逗号,实际API返回如果存在这个问题会导致json_decode解析失败
  2. 实际使用时建议增加异常判断,比如API请求失败、JSON解析异常的场景,避免页面抛出PHP警告。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 06:36:04