2011-09-27 90 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 –