簡體   English   中英

使用PHP獲取JSON數據

[英]Getting JSON data with PHP

如果這已被問過一千次道歉,但我找不到一個關於如何正確地做這個並且在Stack上搜索的好教程即將出現。

我有一個JSON文件,其中包含如下數據:

   {
      "store":"Store 1",
      "cat":"Categories",
      "general_cat":"Categories",
      "spec_cat":"Accessories"
   },
   {
      "store":"Store 1",
      "cat":"Categories",
      "general_cat":"Categories",
      "spec_cat":"Accessories"
   },

其中約有50個條目。 我正在嘗試解析這些數據並將值存儲在變量中。

到目前為止,我已經嘗試過:

$string     = file_get_contents("jsonFile.json");
$json_array = json_decode($string,true);

foreach ($json_array as $key => $value){

    $store = $key -> store;
    $general_cat = $key -> general_cat;
    $spec_cat = $key -> spec_cat;

    if (!is_null($key -> mainImg_select)){
        $cat = $key -> cat;
    }

    echo $headURL;
}

這導致“試圖獲取非對象屬性”錯誤。 我在這做錯了什么?

json_decode的第二個參數告訴函數是將數據作為對象還是數組返回。

對象訪問使用->符號。 要從json_decode返回一個對象, json_decode使用json_decode($jsonString)json_decode($jsonString, false)默認情況下 ,第二個參數為false

$jsonString = '{ "this_is_json" : "hello!" }';

$obj = json_decode($jsonString);

echo $obj->this_is_json // "hello!";

您還可以通過將第二個參數設置為true來將您的json數據作為數組訪問

$jsonString = '{ "this_is_json" : "hello!" }';

$arr = json_decode($jsonString, true);

echo $arr['this_is_json'] // "hello!";

更具概念性的是,PHP json_decode可以返回一個對象數組(而不僅僅是一個對象)或一個關聯數組。

考慮以下json字符串。 此字符串表示json數據結構(花括號)的“集合”(方括號)。

[
    {
        "name": "One"
    },
    {
        "name": "Two"
    }
]

如果我們將這個json分配給變量$string希望這將說明差異

$asObjects = json_decode($string);

$asAssociativeArray = json_decode($string, true);

foreach ($asObjects as $obj) {
    echo $obj->name;
}

foreach ($asAssociativeArray as $arr) {
    echo $arr['name'];
}

看起來您正在請求關聯數組(通過將True作為第二個參數傳遞給json_decode函數),但嘗試將其用作對象。

試試$json_array = json_decode($string,false); 這將返回對象

另外,正如@MatRt所提到的,您需要使用$ value而不是$ key來引用對象

您需要使用數組語法檢索值:

$item['key']

如同

$item->key

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM