-2

I have the following deocoded JSON array. I need to access the "type" inside the context, as well as I need to loop through each of the values in the payload. How do I do that?

 {
   "RequestHeader":  
      {  
                  "mess": "am putting it on my wall....",
                  "created_time": "2010-08-24T09:01:25+0000"  
                  },
    "context" : 

                       {
                           "type": "friends,circles"

                        }

   "payload" [ {12345},{12345} ,{2345}  ]

   }

I tried the following, but it doesn't work

$decoded = json_decode($json_string);

for ($i=0;$i<payload.length;++$i)

{

$id=$decoded->payload[$i];
//do some operation with the id

}
4
  • Enable error reporting. That's not PHP. Commented Oct 31, 2016 at 13:00
  • 1
    That's not valid JSON Commented Oct 31, 2016 at 13:00
  • This answer may be helpful before proceed to server script. Commented Oct 31, 2016 at 13:11
  • what you are doing payload.length what it is? it is not a php variable. Wake up it is php not javascript. Commented Oct 31, 2016 at 13:16

2 Answers 2

0

First of all the JSON you provided is invalid. Supposedly the valid one should look like this

 {
    "RequestHeader": {
        "mess": "am putting it on my wall....",
        "created_time": "2010-08-24T09:01:25+0000"
    },
    "context": {
        "type": "friends,circles"
    },
    "payload": [
        12345,
        12345,
        2345
    ]
 }

After you've fixed the problem with JSON provider it will be quite easy to access data

<?php

$json = <<<'JSON'
{
    "RequestHeader": {
        "mess": "am putting it on my wall....",
        "created_time": "2010-08-24T09:01:25+0000"
    },
    "context": {
        "type": "friends,circles"
    },
    "payload": [
        12345,
        12345,
        2345
    ]
}
JSON;

$data = json_decode($json, true);

$type = $data['context']['type'];
var_dump($type);
foreach($data['payload'] as $id) {
    var_dump($id);
}

Remember to make sure you check that the data actually exists before accessing it, e.g. isset($data['context']['type']) unless you are absolutely sure in it's integrity.

Sign up to request clarification or add additional context in comments.

Comments

-1

When you use json_decode method, the output will be nested arrays So for example to access context type you need to do the following

echo $decoded["context"]["type"];

And to loop on payload you need to do the following

for ($i=0;$i<$decoded["payload"].length;++$i)
{

$id=$decoded["payload"][$i];
//do some operation with the id

}

1 Comment

Not sure how you ended up with an upvote, but this is wrong on several levels.

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.