简体   繁体   中英

Creating “objects” and “arrays” in PHP in a way that would allows JS to distinguish between them

PHP's syntax to create an array (either indexed or assosiative) is the same, aka

$arr = [];

However, json_encode will convert an empty PHP "array" (note the quotes) to an empty JS array ( [] ), which is not desirable in certain situations.

Is there a way I can create an empty assosiative array in PHP, so json_encode will convert it to an empty JS object, aka {} , instead of [] .

Use a stdClass() :

php > $x = new StdClass;
php > echo json_encode($x);
{}

Of course, once it's a stdclass, you wouldn't be able to use it as an array anymore. But this is at least one way of forcing an empty object in JSON, so you could just special-case your code:

if (count($array) == 0) {
   $json = json_encode(new StdClass);
} else {
    $json = json_encode($array);
}

You can use stdClass :

$obj = new stdClass();
echo json_encode($obj);

This gets me the intended {} output.

You can just pass the JSON_FORCE_OBJECT option to the json_encode function. This will force any empty arrays to be objects as well.

JSON_FORCE_OBJECT (integer) Outputs an object rather than an array when a non-associative array is used. Especially useful when the recipient of the output is expecting an object and the array is empty. Available since PHP 5.3.0.

So:

if (empty($array)) {
    $json = json_encode([], JSON_FORCE_OBJECT);
} else {
    $json = json_encode($array);
}

This looks cleaner than converting an object in my opinion.

Or even

$json = json_encode($array, empty($array) ? JSON_FORCE_OBJECT : 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM