0

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

Luuc
  • 99
  • 1
  • 9
  • 1
    By default `json_decode()` will return objects of class `stdClass`. I don't think there's a built-in way to create custom classes. – Barmar Dec 13 '22 at 21:28
  • The short answer is: No. The long answer is: No, but there are various techniques to re-create the objects from the decoded data depending on your requirements. Barmar has posted a version of the simplest method. – Sammitch Dec 13 '22 at 23:52
  • It's also worth noting that PHP does not have typed arrays. At all. The closest you would get is writing something like an `OffersCollection` class that enforces types of its members, but that itself may be overkill for your purposes. TBH most of time we just assume that the array will contain the things it is supposed to, optionally verifying after the fact. – Sammitch Dec 13 '22 at 23:54
  • Tangentially related (framework specific): [How to get class object with $query->row on Codeigniter](https://stackoverflow.com/q/13916194/2943403) Also, maybe relevant: [Fetching all rows as Object with pdo php](https://stackoverflow.com/q/23963326/2943403) And another which is PDO specific: https://phpdelusions.net/pdo/objects – mickmackusa Dec 13 '22 at 23:59
  • Also worth linking: [instantiating a new class in a loop or not in a loop?](https://stackoverflow.com/q/1942313/2943403) and [Mapping Multidimensional Array Objects to Variables in a Class](https://stackoverflow.com/q/23818151/2943403) – mickmackusa Dec 14 '22 at 00:39

1 Answers1

3

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
);
Sammitch
  • 30,782
  • 7
  • 50
  • 77
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Would this remove the parent class and only keep the nested objects? I am currently trying to access properties from the objects via a foreach loop get a nulling error. – Luuc Dec 13 '22 at 21:38
  • 1
    `->offers` just extracts the `offers` array and ignores everything else. I thought that was what you wanted, since you said that was redundant. – Barmar Dec 13 '22 at 21:40
  • 1
    I've refactored it to set a variable to the entire JSON object, and just use `->offers` in the `array_map()`. If there are other top-level properties you can access them from `$data`. – Barmar Dec 13 '22 at 21:42