如何在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
}

试试这样:

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

最新更新