php - 如何仅选择json文件中的一个对象
问题描述
您好我目前正在尝试执行 API 请求。API 发送一个 json 请求,如下所示:
[
{
"name": "Test 1"
"yes-or-no": "yes"
},
{
"name": "Test 2"
"yes-or-no": "no"
}
]
我的问题是,如何选择其中一个yes-or-no
在网站中回显?我试过这样做:
<?php
$status = json_decode(file_get_contents('url to the json file'));
// Display message AKA uptime.
foreach ($status->yes-or-no as $answer) {
echo $answer.'<br />';
}
?>
但是没有用。
如果我弄错了一些术语,我很抱歉,因为我对这样的 API 编码很陌生。
编辑:请看下面的答案。它有效,但现在我的问题是:我如何只显示其中一个?而不是他们两个同时显示。
解决方案
我不确定您要做什么,但也许我可以对这个问题有所了解:
$status = json_decode(file_get_contents('url to the json file'), true);
添加 ", true" 这将使您的 $status 成为数组而不是对象。
foreach ($status as $answer) {
echo $answer['yes-or-no'].'<br />'; //output yes or no
echo $answer['name'].'<br />'; //output test 1 or test 2
}
推荐阅读
- c# - 如何通过 C# 在 Sharepoint Online 中创建共享链接?
- plot - 在 r 中绘制计数数据
- apache-spark - 火花流使用广播包装hbase客户端直接访问启用kerberos的hbase,但我不知道如何刷新令牌
- selenium - org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:69) 处的 java.lang.NullPointerException
- java - 如何在 JPA CriteriaBuilder 中使用位运算符
- powerbi - DAX - 连接多个字符串并忽略空值或空值
- java - @FXML 注入自定义组件不会在Controller中实例化变量并导致NullPointerException
- arrays - 在scala中实现excel Loopup函数
- coldfusion - CFLint - 全局变量警告
- android - 从备份到具有不同配置的新设备上安装与应用程序包一起上传的应用程序会发生什么?