# php生成空对象的方法

**URL:** https://www.shiqidu.com/t/topic/365
**Category:** 开发调优
**Tags:** PHP
**Created:** [2018 年1 月 19 日 14:29 UTC](https://www.shiqidu.com/t/topic/365 "2018-01-19T14:29:16Z")
**Posts on this page:** 1
**Page:** 1

<div class="post-metadata">

### 作者： ![Eureka](https://www.shiqidu.com/user_avatar/www.shiqidu.com/eureka/32/5_2.png) [@Eureka](https://www.shiqidu.com/u/Eureka)
#### 发布日期： [2018 年1 月 19 日 14:29 UTC](https://www.shiqidu.com/t/topic/365/1 "2018-01-19T14:29:16Z")

</div>

因为app的朋友不想在返回的json数据中返回空数组`[]`，想要空对象`{}`，所以在返回json\_encode的数组中就要判断一下是不是空数组，如果是空数组就转为空对象。

```php
if (empty($v)) {  
    if (is_array($v)) {  
        $data[$k] = new \stdClass();  
    } else {  
        $data[$k] = (string)$v;  
    }  
}  

```
