doujue6196 2012-12-14 02:53
浏览 39

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.

  • 写回答

2条回答 默认 最新

  • donglu2761 2012-12-14 03:05
    关注

    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));
    
    评论

报告相同问题?

悬赏问题

  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算