访问嵌套对象和数组

时间:2018-03-19 16:37:17

标签: php arrays

我正在使用Mailgun API。我有一个变量,里面有一些对象和数组,如下所示:

$result =
stdClass::__set_state(array(
   'http_response_body' => 
  stdClass::__set_state(array(
     'items' => 
    array (
      0 => 
      stdClass::__set_state(array(
         'geolocation' => 
        stdClass::__set_state(array(
           'country' => 'UK',
           'region' => '72',
           'city' => 'London',
        )),
         'tags' => 
        array (
        ),
         'mailing-list' => 
        stdClass::__set_state(array(
           'list-id' => 'email@address.com',
           'address' => 'email@address.com',
           'sid' => '123456',
        )),
         'ip' => '123.456.789',
         'log-level' => 'info',
         'id' => 'ABCA',
         'campaigns' => 
        array (
          0 => 
          stdClass::__set_state(array(
             'name' => 'TEST',
             'id' => 'test123',
          )),
        ),
      )),
    ),
   'http_response_code' => 200,
));
?>

我需要访问内部的每一个信息(例如IP,国家,地区),.我尝试了多种解决方案,包括使用foreach

foreach ($result as $row) {
    echo $row->items->ip;
}

然而我一直在

  

捕获致命错误:类stdClass的对象无法转换为字符串

我知道我没有以正确的方式访问数据。你能建议吗?

1 个答案:

答案 0 :(得分:2)

我认为你的意思是循环if (file_exists('update.xml')) { $xml = simplexml_load_file('update.xml'); foreach($xml as $manufacturer){ echo $manufacturer['id'] . PHP_EOL; foreach ($manufacturer as $k => $v) { // `$k` gives you a tagname, // `$v->download` gives value of `download` tag echo $k . $v->download . PHP_EOL; } } } else { exit('Failed to open update.xml.'); } 。你实际做的是循环$result->http_response_body->items似乎不存在。

$result->items