JSON FEED:
{
"Group": [
{
"name": "HolderOne",
"operators": [
{
"username": "ken",
"status": 3
},
.....etc.....
CODE:
<?php
$json = file_get_content('path to feed');
$data=json_decode($json);
echo $data->cGroup[0]->operators[0]->username; //WORKS!
if (is_array($data->Group->operators))
{ foreach($data->Group->operators as $operator)
{if($operator->username == "ken") {echo $operator->status;}}
} else { echo 'NOT AN ARRAY'; } //DOESNT WORK - DISPLAYS NOT AN ARRAY
?>
I am trying to say if the username is Ken (or whatever I specify when I code more) display the correspoding status.
So...
echo $data->Group[0]->operators[0]->username; //WORKS!
but...
foreach($data->Group->operators as $operator) {if($operator->username == "ken") {echo $operator->status;}}
...doesn't - probably something obvious, but can anyone see my problem?
Cheers Andy
2 Answers 2
It would have to be $data->Group[0]->operators, or loop through the Groups and have another loop inside...
foreach($data->Group as $group){
foreach($group->operators as $operator){
if($operator->username == "ken") {echo $operator->status;}
}
}
answered Oct 26, 2012 at 18:12
Billy Moon
58.9k27 gold badges148 silver badges245 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
I think it's true:
foreach($data["Group"]["operators"] as $operators)
{
if($operators["username"] == "ken")
{
echo $operators["status"];
}
else
{
echo 'NOT AN ARRAY';
}
}
answered Oct 26, 2012 at 19:20
Peyman
3771 gold badge4 silver badges11 bronze badges
Comments
lang-php