0

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!

6
  • print_r($newobj); will print all the keys and values for you. Commented Feb 23, 2016 at 20:16
  • 1
    Give us valid json pls Commented Feb 23, 2016 at 20:17
  • Please extract a minimal example anyone can run. Don't give us those snippets and a vague description containing invalid JSON. Commented Feb 23, 2016 at 20:20
  • For inspiration, CakePHP has a Hash.flatten() function which comes close to what you're looking for I think: github.com/cakephp/cakephp/blob/master/src/Utility/… Commented Feb 23, 2016 at 20:25
  • Updated the json snippet, it was missing closing bracket. Commented Feb 23, 2016 at 21:23

1 Answer 1

1
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));
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Pamblam. That worked though, is there a way, I can add something like request1.nest1 - solution1, basically it tries to find a parent and prepends it before displaying?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.