PHP - Fonction json_decode ()

La fonction json_decode () peut décoder une chaîne JSON.

Syntaxe

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

La fonction json_decode () peut prendre une chaîne codée JSON et la convertir en une variable PHP.

La fonction json_decode () peut renvoyer une valeur encodée en JSON dans le type PHP approprié. Les valeurs true, false et null sont respectivement renvoyées comme TRUE, FALSE et NULL. La valeur NULL est retournée si JSON ne peut pas être décodé ou si les données encodées sont plus profondes que la limite de récursivité.

Exemple 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";
      }
   }
?>

Production

Raja
Hyderabad
Telangana

Jai
Secunderabad
Telangana

Exemple 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 . "]";
   }
?>

Production

[name][Raja][Adithya][Jai]