0

Hi I'm currently trying to do an API request. The API sends out a json request like this:

[
 {
  "name": "Test 1"
  "yes-or-no": "yes"
 },
 {
  "name": "Test 2"
  "yes-or-no": "no"
 }
]

My question is, how do I select one of the yes-or-no to echo in the website? I tried doing this:

<?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 />';
}
?>

But didn't work.

I'm sorry if I got some terms wrong, since I'm pretty new to coding APIs like this.

EDIT: Please see the answer below. It works but now my question is: How do I only display one of them? Instead of both of them displaying at the same time.

SappyCS
  • 53
  • 5
  • `$status->{'yes-or-no'}` ?? – Professor Abronsius Oct 21 '21 at 14:33
  • a variable property or occurance name of `yes-or-no` is invalid in PHP ( hyphens are not allowed in variable names). So if you have any control over the returned data from this API ask them to make the names valid – RiggsFolly Oct 21 '21 at 14:39
  • @RiggsFolly It is really not called `yes-or-no`, I'm just really using that as an example currently. – SappyCS Oct 21 '21 at 22:54
  • Dear high reppers, please identify basic questions and close them as duplicates so that Stack Overflow doesn't have to keep collecting redundant content. – mickmackusa Oct 21 '21 at 23:48

2 Answers2

2

I'm not really sure what you are trying to do, but maybe i can shed some light into the question:

$status = json_decode(file_get_contents('url to the json file'), true);

Add ", true" this will make your $status an array instead of an object.

foreach ($status as $answer) {
    echo $answer['yes-or-no'].'<br />'; //output yes or no
    echo $answer['name'].'<br />'; //output test 1 or test 2
}
Schmidl
  • 91
  • 2
  • Why do people always want to convert perfectly good objects into arrays? – RiggsFolly Oct 21 '21 at 14:36
  • For me it‘s just that i prefer the Syntax. I think it‘s easier when working with JavaScript, but maybe that‘s just me. Apart from that, i just tried to help. – Schmidl Oct 21 '21 at 16:05
  • This works, but how do I only display one at a time? Instead of both? – SappyCS Oct 21 '21 at 23:03
  • foreach will loop over all the items. If you would only display one item you can get it via $status[0]['name'] <- this will take the first item $status[1]['name'] will be the second. for a random item you could count the items in the status and display it via a random function. – Schmidl Oct 22 '21 at 06:46
1

Try something like this:

<?php
$statuses = json_decode(file_get_contents('url to the json file'));

foreach ($statuses as $status) {
    echo $status->{'yes-or-no'};
}
?>