Php has an inbuilt JSON Serialising function.
Use that if you can and don't suffer not invented here syndrome.
(PHP 5 >= 5.2.0, PHP 7, PECL json >= 1.2.0)
json_encode — Returns the JSON representation of a value
json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] ) : string
Returns a string containing the JSON representation of the supplied value.
The encoding is affected by the supplied options and additionally the encoding of float values depends on the value of serialize_precision.
Hope it helps!!