phparraysjsonsymfonyjmsserializerbundle

Json_encode / JMS_Serializer, keep numeric key


I have a back-end API in symfony and front in vueJs, In my app, I have a route for getting form definition ...

But for the entityType i need have the choice list so i do this:

$result['choice'] = array_reduce($config->getOption('choice_list')
                    ->getChoices(), function ($carry, $item) {
                        return array_merge($carry, [(string)$item->getId() => (string)$item]);
                    }, []);

In theory this return somethingth like :

[ "0" => "value1", "1" => "value2", "3" => "value3" ... ]
( note, key are not necessary continue)

In practice, debugger say "0" it's numeric so is int! And JMS or json_encode do the same ... and after serialization, I have a simple array without a key!

how can I trick JMS or native PHP function for getting a real associative array?


Solution

  • $result['choice'] = array_reduce($config->getOption('choice_list')
                        ->getChoices(), function ($carry, $item) {
                            return array_merge($carry, ["0{$item->getId()}" => (string)$item]);
                        }, []);
    

    concat "0" front of the id do the trick :)

    i have a "fake" string id in my form ... but when i submit the form ... symfony cast the "01" to int ^^