首页 > 解决方案 > 如何仅选择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 编码很陌生。

编辑:请看下面的答案。它有效,但现在我的问题是:我如何只显示其中一个?而不是他们两个同时显示。

标签: phpjson

解决方案


我不确定您要做什么,但也许我可以对这个问题有所了解:

$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
}

推荐阅读