【问题标题】:Retrieve value from a Json Array从 Json 数组中检索值
【发布时间】:2011-09-27 13:14:14
【问题描述】:

我在从 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>";

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

【问题讨论】:

    标签: php arrays json


    【解决方案1】:

    您的代码存在多个问题:

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

    打开您的error_reporting 级别以获得一些开发帮助。

    【讨论】:

    • 非常感谢马里奥。会听取你的建议:)
    【解决方案2】:
    echo "** -- " . $a_post_data_array[0]['post_title'];
    

    【讨论】:

      【解决方案3】:

      试试这个 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>";     
      

      【讨论】:

        猜你喜欢
        • 2019-08-25
        • 2016-05-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多