2011-09-27 87 views
0

我很難從Json數組中檢索值。我有一個使用json_encode創建的Json數據集。這是怎麼出現使用json_decode並顯示使用print_r的經過:從Json數組中檢索值

Array ([0] => stdClass Object ([postID] => 1961 [postTitle] => Kiss My Fairy [previewThumb] => 2011/09/Kiss-My-Fairy-Ibiza-essentialibiza-2011_feature.jpg [blogContent] => Ibiza has always had a flair for the extravagant, inhibitions are checked in at the airport when the floods of tourists arrive and the locals have embraced a freedom of partying that has turned the quiet Mediterranean island into the Mecca...)) a_post_data_array = 1 

是實現這一功能的代碼如下:

$post_data_URL = "http://myurl.com/news/scrape/facebook-like-chart-ID.php?post_name=kiss-my-fairy"; 

$post_data_response = file_get_contents($post_data_URL); 

$a_post_data_array=json_decode($post_data_response); 

我現在只是需要從該數組檢索一些值用作變量。該數組將只有一組值。我正在使用下面的代碼,但它不起作用。

echo "**** -- " . $a_post_data_array[post_title] . "<br>"; 

任何人都可以請幫忙嗎?對不起,這是如此基本。我一直在網上搜索,但找不到任何這方面的例子。

回答

0

有你的代碼中的多個問題:

  • 首先,你應該指示json_decode給你$data = json_decode($response, TRUE);
  • 純數組,那麼結果數組是一個列表,你必須訪問第一個元素爲$data[0]
  • 您要訪問的條目具有密鑰postTitle,而不是post_title,如示例代碼所示。 (除非這是預定的常數,將無法正常工作。)
  • 而你需要把這些數組鍵加引號,像print $data[0]["postTitle"];

調高你的error_reporting水平有所發展的幫助。

+0

謝謝你這麼多馬里奧。將採取您的意見:) –

0
echo "** -- " . $a_post_data_array[0]['post_title']; 
0

試試這個PHP代碼:

//$post_data_response = file_get_contents("https://raw.github.com/gist/1245028/80e690bcbe6f1c5b46676547fbd396ebba97339b/Person_John.json"); 
//$PersonObject = json_decode($post_data_response); 

// Get Person Object from JSON Source 
$PersonObject = json_decode('{"ID":"39CA2939-38C0-4C4E-AE6C-CFA5172B8CEB","lastname":"Doe","firstname":"John","age":25,"hobbies":["reading","cinema",{"sports":["volley-ball","snowboard"]}],"address":{}}'); 

// Get data from Object 
echo "Person ID => $PersonObject->ID<br>"; 
echo "Person Name => $PersonObject->firstname<br>"; 
echo "Person Lastname => $PersonObject->lastname<br>"; 
echo "Person Age => $PersonObject->age<br>"; 
echo "Person Hobbies => " . $PersonObject->hobbies[0] . "<br>";  
+0

請參閱完整的PHP代碼在URL https://gist.github.com/1245070 –