0

For instance, I have an array of these objects returned in a user_timeline from twitter. The object looks like this:

[{"created_at": "Fri Nov 02 23:44:11 +0000 2012", "id": 264513266083049472, "id_str": "264513266083049472", "text": "@JessLeighMusic do it! This time my dad will be playing!", "source": "\u003ca href=\"http:\/\/twitter.com\/download\/iphone\" rel=\"nofollow\"\u003eTwitter for iPhone\u003c\/a\u003e", "truncated": false, "in_reply_to_status_id": 264489640013217793, "in_reply_to_status_id_str": "264489640013217793", "in_reply_to_user_id": 38814642, "in_reply_to_user_id_str": "38814642", "in_reply_to_screen_name": "JessLeighMusic", "user": {
"id": 143161594,
"id_str": "143161594",
"name": "Mandala Faulkner",
"screen_name": "Mandalastar",
"location": "Ada, Ok",
"description": "I love to sing, play guitar, piano, and flute, but I am still learning everyday. I perform at the Quality Inn the first and third Friday of every month.",
"url": null,
"entities": {
    "description": {
        "urls": []
    }
},

And so on and so forth. Here's my question: when using a foreach in PHP, how to instruct the code to "drill down" to the elements in each {} set? I've never worked with JSON objects before and Twitter's API documentatin is dreadful.

2
  • Why do you need to use foreach? You can simple get an object using json_decode and then access the properties. What are you trying to do? Commented Jul 19, 2013 at 2:11
  • I'm trying to print the text of a tweet from a larger object, like the one above; I just don't know exactly what kind of array the json_decode returns, so I don't know how to drill down to get the info from the sublevels that I'm looking for. Commented Jul 21, 2013 at 1:16

2 Answers 2

2
$list = json_decode($json_text, true);
foreach ($list as $item) {
    // $item is the each {} set you want
}
Sign up to request clarification or add additional context in comments.

Comments

1

json_decode() is your friend here. Turns proper json strings into nested php array()s.

You would then foreach over the resulting array:

$json = "json string here";
$result = json_decode($json);

foreach ($result as $object)
{
    //do stuff
}

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.