繁体   English   中英

PHP检查键是否存在于多维数组和对象组合中,然后获取值

[英]PHP Check if Key Exists in Multidimensional Array and Object Combination then Get Value

我正在查询一个API,得到的响应是一个多维对象对象(stdClass),它也包含数组。 我需要能够检查响应是错误条件还是成功。 如果响应成功,则需要返回TRUE。 如果响应是错误,则需要返回响应中包含的错误消息。 成功和错误的响应格式完全不同。 错误响应如下所示:

object(stdClass)#837 (3) {
  ["errors"]=> array(1) {
                [0]=> object(stdClass)#838 (2) {
                        ["code"]=>int(324)
                        ["message"]=>string(80) "Duration too long, maximum:30000, actual:37081 (MediaId: snf:840912013693931526)"
                    }
                }
  ["httpstatus"]=>int(400)
  ["rate"]=>NULL
}

成功的响应如下所示:

  object(stdClass)#837 (27) {
  ["created_at"]=> string(30) "Sun Mar 12 13:41:43 +0000 2017"
  ["id"]=> int(840920745073102850)
  ["id_str"]=> string(18) "940920795073102850"
  ["text"]=> string(32) "The Details Posted Here"
  ["truncated"]=> bool(false)
  ["entities"]=> object(stdClass)#838 (5) {
                ["hashtags"]=>
    ........ Way More is in the Response but it does not matter...

我尝试将响应更改为数组,然后使用isset来确定是否为错误,如果是,则获取错误详细信息的值,如下所示:

$RESPONSEARRAY = (array) $RESPONSE; 
(isset($RESPONSEARRAY["errors"])) {
$ERRORMSG_CODE= $RESPONSEARRAY['errors'][0]['code'];
$ERRORMSG_MESSAGE = $RESPONSEARRAY['errors'][0]['message'];
$ITWASANERROR = $ERRORMSG_CODE.": ".$ERRORMSG_MESSAGE;
return $ITWASANERROR;
} else {
return true;
}

但是,执行上述操作会给我以下错误:

Fatal error:  Cannot use object of type stdClass as array

任何人都可以建议一种在服务器上开销最小的情况下完成我想做的事情的方法。 也许不需要将stdClass对象转换为数组,或者如果必须这样做,那很好,但是我只需要它即可。 有人可以提供的任何帮助将不胜感激。

下面是访问数组内部对象的正确方法。

$RESPONSEARRAY = (array) $RESPONSE; 
if(isset($RESPONSEARRAY["errors"])) {
   $ERRORMSG_CODE= $RESPONSEARRAY['errors'][0]->code;
   $ERRORMSG_MESSAGE = $RESPONSEARRAY['errors'][0]->message;
   $ITWASANERROR = $ERRORMSG_CODE.": ".$ERRORMSG_MESSAGE;
   return $ITWASANERROR;
} else {
   return true;
}

$RESPONSEARRAY = (array) $RESPONSE; 您可以获得结果:

  ["errors"]=>
  array(1) {
    [0]=>
    object(stdClass)#1 (2) {
      ["code"]=>
      int(324)
      ["message"]=>
      string(80) "Duration too long, maximum:30000, actual:37081 (MediaId: snf:8
40912013693931526)"
    }
  }
  ["httpstatus"]=>
  int(400)

因此, $ERRORMSG_CODE= $RESPONSEARRAY['errors'][0]['code']; 应该是$ERRORMSG_CODE= $RESPONSEARRAY['errors'][0]->code 等等

暂无
暂无

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

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