如何检查JSON对象在PHP中是否为空? [英] How to check if JSON object is empty in 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屋!