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

5
  • 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. Commented Dec 13, 2022 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. Commented Dec 13, 2022 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. Commented Dec 13, 2022 at 23:54
  • Tangentially related (framework specific): How to get class object with $query->row on Codeigniter Also, maybe relevant: Fetching all rows as Object with pdo php And another which is PDO specific: phpdelusions.net/pdo/objects Commented Dec 13, 2022 at 23:59
  • Also worth linking: instantiating a new class in a loop or not in a loop? and Mapping Multidimensional Array Objects to Variables in a Class Commented Dec 14, 2022 at 0:39

1 Answer 1

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
);
Sign up to request clarification or add additional context in comments.

3 Comments

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.
->offers just extracts the offers array and ignores everything else. I thought that was what you wanted, since you said that was redundant.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.