简体   繁体   中英

Decoding nested json object to php class

I am working with a json file as shown below:

{
  "offers": [
    {
      "offerId": "5",
      "retailerId": "0"
    },
    {
      "offerId": "6",
      "retailerId": "1"
    },
    {
      "offerId": "7",
      "retailerId": "2"
    }
  ]
}

I am used to working with OOP in Java and C# and would like to know if it is possible to parse this json object to a class so I can easily work with it in PHP. As you can see each offer is nested in the offers parent. This parent is redundant, is there a way to save al the nested objects in an array which has objects of type Offer (php class)?

There's nothing built-in, but you can do it easily in your own code.

$data = json_decode($json);
$offers_objects = array_map(
  function($o) {
    return new Offer($o->offerId, $o->retailerId);
  },
  $data->offers
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM