Hello @kartik,
Php has an inbuilt JSON Serialising function.
json_encode
Use that if you can and don't suffer not invented here syndrome.
json_encode
(PHP 5 >= 5.2.0, PHP 7, PECL json >= 1.2.0)
json_encode — Returns the JSON representation of a value
Description
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!!
Thank you!!