获取数组对象中的键值

时间:2018-03-08 10:03:44

标签: php

我在获取数组中键的值时遇到问题。我对PHP并不是很深入,并且在某些时候迷路了。

我的结果:

stdClass Object(
  [code] => 200
  [status] => success
  [message] => 
  [data] => Array(
    [0] => stdClass Object(
      [vps] => smtp2 - 687
      [hardbounce_desc] => host gmail - smtp - in .l.google.com [64.233 .164 .26] said: 550 - 5.1 .1 The email account that you tried to reach does not exist.Please
                  try 550 - 5.1 .1 double - checking the recipient 's email address for typos or 550-5.1.1 unnecessary spaces. Learn more at 550 5.1.1 https://support.google.com/mail/?p=NoSuchUser x90si7716568ljb.275 - gsmtp (in reply to RCPT TO command) 
      [hardbounce_time] => 2018-03-08 09:50:00 [account] => my.smtp [injected_time] => 2018-03-08 09:49:59 [message_id] => 61375aa0f937a2fcd8.04158271_65b85dbf1016581ba7710e6f5a799d28@api.emaillabs.net.pl 
      [ok_desc] => 
      [ok_time] => 
      [open_desc] => 
      [open_time] => 
      [postfix_id] => Array ( 
        [0] => 3zxkjM4tJqz8rgnS 
        [1] => 3zxkjM5xSRz1Y5j6 
      ) 
      [tracking] => Array ( ) 
      [tags] => Array ( ) 
      [to] => mymail@mail.com [uid] => 56aa510e20123485c0068bafde397e23 
      [from] => testemail 
      [subject] => bbbbbbb 
      [created_at] => 2018-03-08 09:49:59 
      [updated_at] => 
      [id] => 5aa0f9c0d26d44a191b7cbe5 
    ) 
  ) 
  [req_id] => lbUSoGjS8K 
)

我要做的是获得hardbounce_descok_desc这样的价值:

if ($json->data['hardbounce_desc'] != null) {
        echo 'hardbounce';
    }
if ($json->data['ok_desc'] != null) {
        echo 'ok';
    }

但这不是它的工作原理。我的问题是如何检查密钥harbounce_descok_desc的值是否为空。

1 个答案:

答案 0 :(得分:2)

$data是一个包含一个对象的数组。试试这个:

if (isset($json->data[0]) && isset($json->data[0]->hardbounce_desc)) {
    echo 'hardbounce';
}
if (isset($json->data[0]) && isset($json->data[0]->ok_desc)) {
    echo 'ok';
}

全面检查:

if (is_object($json) && 
    isset($json->data) &&  is_array($json->data) && 
    !empty($json->data) && 
    is_object($json->data[0]) && 
    isset($json->data[0]->hardbounce_desc)) 
{
    echo 'hardbounce';
}