PHP中的空数组 - > JSON - > JS = Javascript中的空数组。 如何获得空对象?

So here is the basis for building my JSON response back to my JS.

$this->_response['vendor'] = array();

foreach ($_results as $_row) {
    $this->_response['vendor'][$_row['id']] = $_row;
}

echo(json_encode($this->_response));

This is fine and builds objects in javascript fine, unless there were no results. In that case, the php sees it as an empty numeric array, instead of an associative array. This then comes down to javascript and converts to an empty array instead of an empty object.

I know I can fix this in a number of ways by checking things, pre-declaring the variables as objects in javascript etc. What I'm wondering is if there is a way to declare an empty associative array in php, or some other way to force json_encode to create an object ("{}") instead.

I suppose the most reasonable answer here is that there's probably no point in delivering an empty array or object in the first place. Simple checks for existence in the javascript would then handle the problem.

if (count($_results)) {

    $this->_response['vendor'] = array();

    foreach ($_results as $_row) {
        $this->_response['vendor'][$_row['id']] = $_row;
    }
}
echo(json_encode($this->_response));

It's a known limitation of PHP - since it doesn't support JavaScript types natively (eg. objects), decoding and then encoding again may lead to data loss.

I use a workaround like this to keep JSON in tact:

/**
 * @param $input
 * @return array
 */
public static function safeDecode($input) {
    // Fix for PHP's issue with empty objects
    $input = preg_replace('/{\s*}/', "{\"EMPTY_OBJECT\":true}", $input);

    return json_decode($input, true);
}

/**
 * @param array|object $input
 * @return string
 */
public static function safeEncode($input) {
    return preg_replace('/{"EMPTY_OBJECT"\s*:\s*true}/', '{}', json_encode($input));
}

It's not ideal but it works. Note that you can:

  • json_decode() to objects, which is default manner. Then empty objects are not lost, but most modern frameworks REQUIRE arrays because most collection manipulation tools work with arrays. Therefore, in most cases it's not a viable option;
  • You could force json_encode() to encode empty arrays to objects but then you will lose empty arrays - not a nice option either.

Therefore, a work around like mine shown above is perhaps the only option at this moment. In short, you have to extend PHPs json_encode() and json_decode(). Unfortunately PHP doesn't allow built-in function overloading so you have to define functions with different names.