0

I am getting the contents of a facebook api call that will return all the posts made to a facebook group. So all the posts/comments on that post.

$data = json_decode(file_get_contents($url2));

foreach($data as $post){
    foreach $post as $subpost)
    {
     ...etc
    }
}

The problem I have here is that I will need to use 3 nested foreach loops in order to actually get the data I want. How do I get the first element of $data without having to use a foreach?

e.g. something like $data[0] (which doesn't work). How does a foreach loop iterate through an object so I can just manually write it since I only want 1 single object thats nested inside arrays.

edit object(stdClass)#1 (2) { ["data"]=> array(25) { [0]=> object(stdClass)#2 (10)...

i want to access the final object that contains 10 pieces of data.

3
  • 2
    can you show the var_dump($data) Commented Jun 2, 2014 at 12:02
  • Yes, show what the data looks like if you want a solution Commented Jun 2, 2014 at 12:02
  • sidenote: you can use json_decode($return_value, true), to make it an array if objects bothers you Commented Jun 2, 2014 at 12:09

4 Answers 4

2

$data = json_decode(file_get_contents($url2), true);

will return an array and you can access it via an index like $data[0].

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

Comments

1

Try to use like below - just pass true in second argument , it will convert object into array so you can use it as array.

$data = json_decode(file_get_contents($url2), true);
foreach($data as $post){
    foreach $post as $subpost)
    {
        ...etc
    }
}

Comments

1

You should do

$data = json_decode(file_get_contents($url2),true);

To convert it to a array then try

$data[0]

Comments

0

You can use $post instead of $data.. indexing of $post depends on what kind of data you are receiving through json. If it is a 2-dimensional array,You can use $post[0]['index'] or if it is a single-dimensional array,you can use $post['index'], which will give you the exact indexed item.

Comments

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.