PHP - json_decode() 函式



json_decode() 函式可以解碼 JSON 字串。

語法

mixed json_decode( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )

json_decode() 函式可以接收一個 JSON 編碼的字串並將其轉換為 PHP 變數。

json_decode() 函式可以將 JSON 中編碼的值返回為相應的 PHP 型別。值 true、false 和 null 分別返回 TRUE、FALSE 和 NULL。如果無法解碼 JSON 或編碼資料深度超過遞迴限制,則返回 NULL。

示例 1

<?php 
   $jsonData= '[
                  {"name":"Raja", "city":"Hyderabad", "state":"Telangana"}, 
                  {"name":"Adithya", "city":"Pune", "state":"Maharastra"},
                  {"name":"Jai", "city":"Secunderabad", "state":"Telangana"}
               ]';

   $people= json_decode($jsonData, true);
   $count= count($people);

   // Access any person who lives in Telangana
   for ($i=0; $i < $count; $i++) { 
      if($people[$i]["state"] == "Telangana") {
         echo $people[$i]["name"] . "\n";
         echo $people[$i]["city"] . "\n";
         echo $people[$i]["state"] . "\n\n";
      }
   }
?>

輸出

Raja
Hyderabad
Telangana

Jai
Secunderabad
Telangana

示例 2

<?php
   // Assign a JSON object to a variable
   $someJSON = '{"name" : "Raja", "Adithya" : "Jai"}';
 
   // Convert the JSON to an associative array
   $someArray = json_decode($someJSON, true);
 
   // Read the elements of the associative array
   foreach($someArray as $key => $value) {
      echo "[" . $key . "][" . $value . "]";
   }
?>

輸出

[name][Raja][Adithya][Jai]
php_function_reference.htm
廣告