Symfony 5 php object to array conversion

Symfony 5 php object to array conversion

By d-erf | Devtips | 13 Oct 2020


Hello all!

 

 

Today one tip (for a tip!), for automatic, correct, recursive, pain-free method to converting php object to json, under symfony 5 php framework.

You know it's a common need but not so well addressed in fact, with such a simplicity, avoiding programming an exact 1:1 manual mapping or programming it's own function to do that.

It my case, i get mongo odm results from a doctrine repository findall(), and get an array of objects (templates here).

I wanted an easy, recursive (automatique) object conversion to php associative array, to make use of it.

Let me show you a convenient way to do this:

 

We'll use symfony's serializer module's components (serializer is part of the base deployment with composer, so no need in installing anything).

 

 

In object class:

 

use Symfony\Component\Serializer\Encoder\JsonEncoder;

use Symfony\Component\Serializer\Encoder\XmlEncoder;

use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;

use Symfony\Component\Serializer\Serializer;







class Template { ...  

   // iders

   // getters

   // setters

   // issers

   // whatever

   // and a special function for json conversion, note it's a public function

   public static function converttoarray($templates) {

      $encoders = [newXmlEncoder(), newJsonEncoder()];
      $normalizers = [newObjectNormalizer()];
      $serializer = newSerializer($normalizers, $encoders);

      $i = 0;

      foreach($templates as $template) {

         $templates[$i] = json_decode($serializer->serialize($template, 'json'), true);

         $i++;

      }

      return$templates;

    }

} 

 

 

To be called in a controller:

 

$result['templates'] = $dm->getRepository(Template::class)->findAll();

$result['templates'] = Template::converttoarray($result['templates']);

 

 

Ok, that's done! Enjoy!

 

 

Feel free to tip me, it will encourage me to publish more interesting and useful content!

 

Have you read my other posts, click here!

 

Don't you know publish0x? It's an alternative and innovative free blogging platform paying in crypto just for viewing (with their bat coins pool) and for authoring, clic here to try

 

Follow me on publish0x, and on twitter!

 

See you all!

How do you rate this article?

2



Devtips
Devtips

Dev tips and tricks

Publish0x

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.