I want to dump an associative array to file using PHP. Sometimes the result can be empty and in this case I want the content of the file be exactly : { } so that I can process all files in the same way.
However, I can only initialize a simple array in PHP, and so the output in the file is always this : [ ]. I already tried adding a dummy entry to the associative array and then deleting the entry again so that the array is empty, but then again [ ] is the output in the file.
The json_encode function has an option that will coerce arrays into objects where ever contextually appropriate - i.e. associative arrays but this also includes empty arrays, for example:
$array = array(
'foo' => array(),
'bar' => array()
);
echo json_encode($array, JSON_FORCE_OBJECT); // {"foo":{},"bar":{}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With