繁体   English   中英

如何访问 stdClass 多级对象或数组?

[英]How to access stdClass Multi level object or array?

我不得不在 PHP 中发出一个特别复杂的 SOAP 请求,并且似乎已经收到了对象内的对象。 我需要获得一个特定的值,例如“session_token”。 我可以 var_dump 请求,甚至将其转换为数组,但我无法访问单个元素。 请帮忙!

对象:

stdClass Object ( [login_response] => stdClass Object 
    ( [response_context] => stdClass Object 
        ( [session_token] => b1043dcb82625701188ffff03572 
            [response_status] => OK [response_message] => Login successful 
                )))) 

转换后的数组:

Array ( [0] => 
    Array ( [response_context] => 
        Array ( [session_token] => b1043dcb82625701188ffff03572 
            [response_status] => OK [response_message] => Login successful
             ) ) ) 

一旦它是一个数组,它就只是一个数组,例如

$obj->foo->bar->baz

将只是

$arr['foo']['bar']['baz']

所以在你的情况下

$arr[0]['response_context']['response_status'] -> "OK"

如果你把它作为一个对象,并没有理由不这样做。

echo $obj->login_response->response_context->session_token;
echo $obj->login_response->response_context->response_status;
echo $obj->login_response->response_context->response_message;

会输出

b1043dcb82625701188ffff03572
OK
Login successful 

通常要访问对象的任何键,需要这样调用

echo $obj->key;

但是,由于这是一个多级对象,要访问该元素,您必须像下面这样编码。

echo $obj->login_response->response_context->session_token;

结果将是b1043dcb82625701188ffff03572

同样,通常要访问数组的任何键,都需要这样调用

echo $arr['key'];

但是,由于这是一个多级数组,要访问元素,您必须像下面这样编码。

echo $arr[0]['response_context']['session_token'];

输出是b1043dcb82625701188ffff03572

这里, 0$arr数组的键。

response_context0的键。

session_tokenresponse_context的关键。

您可以使用此服务,数组可视化器,这将帮助您定位和仅提取您需要的内容。 刚刚过去的 print_r 输出。 就是这样。 试一试

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM