Ok I have banged my head for the last 24hrs and cannot figure this out after testing and reading SO. I have a JSON file that I need to parse and for some reason I cannot get the right combination of code to echo anything out other than "Array" or "Trying to get property of non-object" or "Invalid argument supplied for foreach()". Here is the full JSON that I am trying to iterate over. I need to print out the name of each 'project', the 'dataset' in each project, and the 'permissions' for each 'dataset'. I am building this JSON myself, so I can change the format if necessary.
$data = json_decode($json, true);
Outputs JSON below:
[
[
{
"projects":[
{
"project":"test-project-1",
"datasets":[
{
"dataset":"testing1",
"permissions":[
{
"role":"READER",
"google_group":"[email protected]"
}
]
},
{
"dataset":"testing2",
"permissions":[
{
"role":"OWNER",
"google_group":"[email protected]"
}
]
},
{
"dataset":"testing3",
"permissions":[
{
"role":"READER",
"google_group":"[email protected]"
}
]
},
{
"dataset":"testing4",
"permissions":[
{
"role":"WRITER",
"google_group":"[email protected]"
}
]
}
]
},
{
"project":"test-project-2",
"datasets":[
{
"dataset":"testing1",
"permissions":[
{
"role":"READER",
"google_group":"[email protected]"
}
]
},
{
"dataset":"testing2",
"permissions":[
{
"role":"READER",
"google_group":"[email protected]"
}
]
},
{
"dataset":"testing3",
"permissions":[
{
"role":"READER",
"google_group":"[email protected]"
}
]
},
{
"dataset":"testing4",
"permissions":[
{
"role":"READER",
"google_group":"[email protected]"
}
]
}
]
}
]
}
]
]
I have tried things like:
foreach($data->projects as $output)
{
echo $output->project . "\n";
foreach($output->datasets as $datasets)
{
echo $output->dataset . "\n";
}
}
Thank you for the help!
EDIT: Working code that parses the JSON above:
$projects = $json['projects'];
foreach ($projects as $project) {
echo $project['project'] . "<br>";
foreach ($json['projects'][0]['datasets'] as $datasets){
echo $datasets['dataset'] . "<br>";
foreach ($json['projects'][0]['datasets'][0]['permissions'] as $permissions){
echo $permissions['role'] . "<br>";
echo $permissions['google_group'] . "<br>";
}
}
}
var_dump($output->dataset);