且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查JSON对象在PHP中是否为空?

更新时间:2022-03-10 07:14:58

您要反序列化多少个对象?除非事实证明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.