سؤال

I want to dump an associative array to file with 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.

هل كانت مفيدة؟

المحلول

Cast it to object before encoding:

json_encode((object) $array);

نصائح أخرى

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":{}}

Another answer to this is to use ArrayObject instead of [] when initialising the variable.

The following illustrates the problem. When the associative array is empty, it is JSON encoded as '[]':

$object = [];
echo json_encode($object); // you get '[]'

$object['hello'] = 'world';
echo json_encode($object); // you get '{hello: "world"}'

Instead, keep everything the same, but when you declare the $object, use ArrayObject:

$object = new ArrayObject;
echo json_encode($object); // you get '{}'

$object['hello'] = 'world';
echo json_encode($object); // you get '{hello: "world"}'

The reason this is a good alternative is because using (object) [] converts the variable to an stdClass meaning you have to access the properties using $variable->property. However, if all your existing code was written using $variable['property'], then using (object) [] means you will have to change all of that code, when you can instead just use new ArrayObject.

Link to ArrayObject that has been available since PHP5

Your going to have to check if the array is empty.

if (empty($array_to_dump)) {
    print ':{}';
} else {
    print serialize($array_to_dump);
}

However, the array you get back when you unserialize should be exactly the same either way... an empty array.

Edit: or use the above, even better.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top