onlyme
onlyme

Reputation: 587

Parsing Decoded nested/mixed JSON in PHP

I'm trying to parse a full JSON structure. I've been able to get individual nested objects, but I was hoping it could be much simple than looking for each nested structure.

Here's the JSON structure I have:

{
"request1": {
    "nest11": "solution11",
    "nest12": "solution12"
},
"request2": {
    "nest21": "solution21",
    "nest22": "solution22"
},
"request3": true,
"request3": {
    "nest31": "solution31",
    "nest32": "solution31",
    "nestnest1": {
        "nestnest11": "nestsolution11",
        "nestnest12": "nestsolution12"
    },
    "nestrequest2": {
        "nestrequest21": [{
            "nestnest21": "solution21",
            "nestnest22": "solution22"
        }]
    },
    "request4": "solution4"
}
}

When I get the response from an API, let's say $serverResponse, I'm decoding to get object

$newobj = json_decode($serverResponse);

foreach ($newobj->request1 as $key=>$value) {
  $request1 = "request1.".$key.": <b>". $value."</b><br/>";
  }

I then send it back to the front end to print it. Question is how do I do it so I don't have to go through each objects and get individual values. I need to print all the key values whether nested or not. Thanks for any pointers and help!

Upvotes: 0

Views: 150

Answers (1)

I wrestled a bear once.
I wrestled a bear once.

Reputation: 23379

function recursivePrinter($data){
    foreach($data as $k=>$v){
        if(is_array($v)) recursivePrinter($v);
        else echo "$k - $v";
    }
}
recursivePrinter(json_decode($response, true));

function recursivePrinter($data, $nested=""){
    foreach($data as $k=>$v){
        if(is_array($v)){ recursivePrinter($v, $k); }
        else echo "$nested.$k - $v";
    }
}
recursivePrinter(json_decode($response, true));

Upvotes: 1

Related Questions