如何检查JSON对象在PHP中是否为空? [英] How to check if JSON object is empty in PHP?

查看:615
本文介绍了如何检查JSON对象在PHP中是否为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用PHP读取JSON数据,并且该数据包含空对象(例如{}).所以问题是,我必须以不同的方式处理对象为空但无法找到足够好的方法进行检查的情况. empty(get_object_vars(object))看起来太吓人了,效率很低.有检查的好方法吗?

I'm reading JSON data with PHP and that data contains empty objects (like {}). So the problem is, I have to handle the case when object is empty in different manner but I can't find good enough way to do the check. empty(get_object_vars(object)) looks too scary and very inefficient. Is there good way to do the check?

推荐答案

您要反序列化多少个对象?除非事实证明empty(get_object_vars($object))或强制转换为主要的速度下降/瓶颈,否则我不会担心– Greg的解决方案就可以了.

How many objects are you unserializing? Unless empty(get_object_vars($object)) or casting to array proves to be a major slowdown/bottleneck, I wouldn't worry about it – Greg's solution is just fine.

尽管如此,我建议在解码JSON数据时使用$associative标志:

I'd suggest using the the $associative flag when decoding the JSON data, though:

json_decode($data, true)

这会将JSON对象解码为普通的旧PHP数组,而不是作为stdClass对象.然后,您可以使用empty()检查空对象,并创建用户定义类的对象,而不是使用stdClass,从长远来看,这可能是个好主意.

This decodes JSON objects as plain old PHP arrays instead of as stdClass objects. Then you can check for empty objects using empty() and create objects of a user-defined class instead of using stdClass, which is probably a good idea in the long run.

这篇关于如何检查JSON对象在PHP中是否为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆