检查对象树中是否存在对象

时间:2016-11-09 14:21:45

标签: php json

解码JSON字符串后,我会得到很多嵌套对象。例如

{
    clients:
    {
        latest:
        {
            business:
            {
                name:
                {

                }
            },
            personal:
            {
                name:
                {

                }
            }
        },
        first:
        {

        }
    }
}

现在我试图访问$result->clients->latest->business->name

如果latest不存在,那么我会收到通知,说明我试图获取非对象的属性(因为latest没有因此存在是非客体的,因此我无法调用->name)。

如何查看对象路径'存在而不做

isset($result) ? isset($result->clients) ? isset($result->clients->latest) ...

2 个答案:

答案 0 :(得分:0)

$array=json_decode($result,true);
if(isset($array['clients']['latest']['business']['name']))
{
 //do something...
}

通过json_decode($result,true)函数,您可以将json转发到数组,然后检查是否设置了值。

答案 1 :(得分:0)

使用try catch:

try{  
    $name= $result->clients->latest->business->name;
}catch(Exception $e){
    $name = '';
}