2013-07-19 132 views
0

例如,我有一個從twitter的user_timeline返回的這些對象的數組。對象看起來像這樣:如何遍歷PHP中的JSON對象

[{"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 documentatin是可怕的。

+0

爲什麼你需要使用的foreach?您可以使用'json_decode'簡單地獲取對象,然後訪問屬性。你想做什麼? –

+0

我試圖從一個更大的對象,如上面的一個打印推文的文本;我只是不知道json_decode返回的是什麼類型的數組,所以我不知道如何深入瞭解我所尋找的子平面的信息。 – rainydaymatt

回答

1

json_decode()是你的朋友在這裏。將適當的json字符串轉換爲嵌套的php array() s。

那麼您需要foreach所產生的陣列上:

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

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