sandy sandy - 12 days ago 6
PHP Question

PHP get json object name

I have json array like that

{
"STATUS": "SUCCESS",
"MESSAGE": "",
"DATA": {
"list": [
{
"val0": {
"hidden": "0",
"rate": "10"
}
},
{
"val1": {
"hidden": "0",
"rate": "20"
}
}
],
"status": "Provisioned"
}
}


I want to get the object name of
DATA>list>
.
I tried with
get_class($list[0])
but the output is
stdClass
. Output should be
val0
.How can I try. Please help

Answer

Use json_decode, list is also an array, Therefor first key(0) represent val0, and If you want to get inner content of the val0, then you have to loop it again.

$data = '{
  "STATUS": "SUCCESS",
  "MESSAGE": "",
  "DATA": {
    "list": [
      {
        "val0": {
          "hidden": "0",
          "rate": "10"
        }
      },
      {
        "val1": {
          "hidden": "0",
          "rate": "20"
        }
      }
    ],
    "cpe_status": "Provisioned"
  }
}';

$data = json_decode($data, true);

foreach($data['DATA']['list'][0] as $key=>$value){
    echo $key; // return val0
    echo "<br/>";
    // to get val0 inner content
    foreach($value as $item=>$list){
        echo $item." - ".$list; // return val0 inner data
        echo "<br/>";   
    }
}

// alternative way for loop val0 inner content
foreach($data['DATA']['list'][0]['val0'] as $key=>$value){
    echo $key." - ".$value; // return val0 inner data
    echo "<br/>";   
}
Comments