Home > database >  Decoding nested json object to php class
Decoding nested json object to php class

Time:12-15

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)?

CodePudding user response:

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
);
  • Related