从Json数组中检索值

时间:2011-09-27 13:14:15

标签: php arrays json

我在从Json数组中检索值时遇到了困难。我有一个使用json_encode创建的Json数据集。这是使用json_decode并使用print_r显示后的显示方式:

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>";

有人可以帮忙吗?对不起,这太基础了。我一直在网上搜索,但找不到任何这方面的例子。

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您的代码存在多个问题:

  • 首先,您应该指示json_decode为您提供一个包含$data = json_decode($response, TRUE);
  • 的纯数组
  • 然后结果数组是一个列表,您必须以$data[0]
  • 的形式访问第一个元素
  • 您要访问的条目的密钥为postTitle,而不是post_title,如您的示例代码所示。 (除非那个预定义的常量不起作用。)
  • 您需要将这些数组键放在引号中,例如print $data[0]["postTitle"];

提高error_reporting级别以获得一些开发帮助。

答案 2 :(得分: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>";