Serializer – array to Object

To convert from an array (including multi-dimensional arrays) to an object, the following code might help!

Ref; https://symfony.com/doc/current/components/serializer.html

// all callback parameters are optional (you can omit the ones you don't use)
$extractor = new PropertyInfoExtractor([], [new PhpDocExtractor(), new ReflectionExtractor()]);
$normalizer = new ObjectNormalizer(null, null, null, $extractor);
$serializer = new Serializer(
    [
        $normalizer,
        new ArrayDenormalizer(),
    ]
);

$obj = $serializer->denormalize(
    $data,
    Member::class,
    null,
    [ObjectNormalizer::DISABLE_TYPE_ENFORCEMENT => true]
);

Symfony

This can also be achieved by installing the following packages, which Symfony will pickup & use with it’s serializer;

composer require phpdocumentor/reflection-docblock
composer require symfony/property-info

Then, in your service (or controller);

public function __construct(SerializerInterface $serializer) {
    $this->serializer = $serializer;
}

And in your code;

$obj = $this->serializer->denormalize(
    $rowData,
    Member::class
);

You can also lessen the enforcement of variable-types (strings vs ints) with the following;

$obj = $serializer->denormalize(
    $data,
    Member::class,
    null,
    [ObjectNormalizer::DISABLE_TYPE_ENFORCEMENT => true]
);

Ref; https://symfony.com/doc/current/components/property_info.html

Leave a Reply