Search code examples
phpmysqljsonserver-side

Fetch complex JSON object with php


I have in my server side my json object in such format:

{"page_1":{
   "stats":{
      "s1":10, "s2": 20}
    },
   "rules":{
      "rule1":{
       "x": 2, "type":"normal"}
      "rule2":{
       //etc
        }
     }
  },
 "page_2":{
   //etc
  }
}

How can I get access to different element using foreach for example, because I need to save them into db.

UPDATE: I tried that but in vain:

foreach ($data as $key => $value) {
    echo $key."\n";
    foreach ($value as $k => $v) {
        echo $k." -- ".$v."\n";
    }

}


Solution

  • Try

    $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
    $myarr = json_decode($json,true);
    foreach($myarr as $key=>$val){
        echo $key, '=>' ,$val , "\n";
    }
    

    You are working with normal PHP array here.

    Your code modified (not tested)

    foreach ($data as $key => $value) {
        echo $key."\n";
        echo "heeeeeeeeeeeeeeeeeere: ", $key['stats']['s1'] , "\n";
        foreach ($value as $k => $v) {
            echo $k," -- ",$v,"\n";
        }
    }