如何在PHP中迭代JSON对象

时间:2013-07-19 01:44:55

标签: php json

例如,我在twitter的user_timeline中返回了这些对象的数组。该对象如下所示:

[{"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": []
    }
},

依此类推。这是我的问题:在PHP中使用foreach时,如何指示代码“向下钻取”到每个{}集合中的元素?我之前从未使用过JSON对象,Twitter的API文档很糟糕。

2 个答案:

答案 0 :(得分:1)

json_decode()是你的朋友。将正确的json字符串转换为嵌套的php array() s。

然后你会在结果数组上foreach

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

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

答案 1 :(得分:1)

$list = json_decode($json_text, true);
foreach ($list as $item) {
    // $item is the each {} set you want
}