iMasterDesign
iMasterDesign

Reputation: 23

Json decode in PHP and how to read the key value

I have a json $result = json_decode($result); PHP JSON EX:

  [
  {
      "X": "Teste1 X",
      "Y": "Teste1 Y",
      "Z": "Teste1 Z",
      "A": {
          "C": "Teste1 C"
      },
      "B": {
          "D": "Teste1 D"
      }
  }
  ]

How to read the key value "A" and "B"?

Key value "C" e "D" in "A" e "B"?

$result = json_decode($result);

foreach ($result as $key => $value) {
    $strx    = $value->X;
    $stry    = $value->Y;
    $strz    = $value->Z;
    if($key == "A") {
        $strA = $value->C;
    }
    if($key == "B") {
        $strB = $value->D;
    }
    $str1    = $value->1;
    $str2    = $value->2;
    $str3    = $value->3; 
}

Upvotes: 2

Views: 8302

Answers (3)

Jaydip Bhingradiya
Jaydip Bhingradiya

Reputation: 338

Hello this is the the way we can easy get the all the value to the particular JSON.

<?php

$result = json_decode('{
      "X": "Teste1 X",
      "Y": "Teste1 Y",
      "Z": "Teste1 Z",
      "A": {
          "C": "Teste1 C"
      },
      "B": {
          "D": "Teste1 D"
      }
  }');

foreach ($result as $key => $value) {
   if($key == "A") {
        $strA = $value->C;
       echo $strA;
       echo "<br/>";
    }else if($key == "B") {
        $strB = $value->D;
        echo $strB;
        echo "<br/>";
   }else{
       echo $value;
       echo "<br>";
   }

}?>

Upvotes: 1

Armin Sam
Armin Sam

Reputation: 933

You can pass true as second parameter to json_decode() in order to get the result in associative array format:

$result = json_decode($result, true);

Then you can simply use the array to get the values you want:

$valueA = $result[0]['A'];
$valueCinA = $result[0]['A']['C'];

Upvotes: 0

TheGentleman
TheGentleman

Reputation: 2362

Because your JSON is wrapped in [] it will be treated as an indexed array and as such your $key variable will be the index of the value (e.g. 0,1,2,etc).

So to answer your question, to get the value of A replace

if($key == "A") {
    $strA = $value->C;
}
if($key == "B") {
    $strB = $value->D;

With

if( isset($value->A)) {
    $strA = $value->A->C;
}
if(isset($value->B)) {
    $strB = $value->B->D;

What are you trying to get with $value->1, $value->2, and $value->3?

Upvotes: 3

Related Questions