1Serializing arrays and hashes 2============================= 3 4Introduction 5------------ 6Serializing arrays and hashes (a concept that in PHP has not explicit boundaries) 7can be challenging. The serializer offers via ``@Type`` annotation different options 8to configure its behavior, but if we try to serialize directly an array 9(not as a property of an object), we need to use context information to determine the 10array "type" 11 12Examples 13-------- 14 15In case of a JSON serialization: 16 17.. code-block :: php 18 19 <?php 20 21 // default (let the PHP's json_encode function decide) 22 $serializer->serialize([1, 2]); // [1, 2] 23 $serializer->serialize(['a', 'b']); // ['a', 'b'] 24 $serializer->serialize(['c' => 'd']); // {"c" => "d"} 25 26 // same as default (let the PHP's json_encode function decide) 27 $serializer->serialize([1, 2], SerializationContext::create()->setInitialType('array')); // [1, 2] 28 $serializer->serialize([1 => 2], SerializationContext::create()->setInitialType('array')); // {"1": 2} 29 $serializer->serialize(['a', 'b'], SerializationContext::create()->setInitialType('array')); // ['a', 'b'] 30 $serializer->serialize(['c' => 'd'], SerializationContext::create()->setInitialType('array')); // {"c" => "d"} 31 32 // typehint as strict array, keys will be always discarded 33 $serializer->serialize([], SerializationContext::create()->setInitialType('array<integer>')); // [] 34 $serializer->serialize([1, 2], SerializationContext::create()->setInitialType('array<integer>')); // [1, 2] 35 $serializer->serialize(['a', 'b'], SerializationContext::create()->setInitialType('array<integer>')); // ['a', 'b'] 36 $serializer->serialize(['c' => 'd'], SerializationContext::create()->setInitialType('array<string>')); // ["d"] 37 38 // typehint as hash, keys will be always considered 39 $serializer->serialize([], SerializationContext::create()->setInitialType('array<integer,integer>')); // {} 40 $serializer->serialize([1, 2], SerializationContext::create()->setInitialType('array<integer,integer>')); // {"0" : 1, "1" : 2} 41 $serializer->serialize(['a', 'b'], SerializationContext::create()->setInitialType('array<integer,integer>')); // {"0" : "a", "1" : "b"} 42 $serializer->serialize(['c' => 'd'], SerializationContext::create()->setInitialType('array<string,string>')); // {"c" : "d"} 43 44 45.. note :: 46 47 This applies only for the JSON serialization. 48