# php生成空对象的方法

**URL:** <https://www.shiqidu.com/t/topic/365>\
**Category:** 开发调优\
**Tags:** PHP\
**Created:** [January 19, 2018, 2:29pm UTC](https://www.shiqidu.com/t/topic/365 "2018-01-19T14:29:16Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Leon](https://www.shiqidu.com/user_avatar/www.shiqidu.com/leon/32/5_2.png) [@Leon](https://www.shiqidu.com/u/Leon)\
**Post date:** [January 19, 2018, 2:29pm 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;  
    }  
}  

```
