iMasterDesign iMasterDesign - 1 month ago 10
JSON Question

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;
}

Answer

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?