douwei1921 2018-10-18 11:59
浏览 163
已采纳

PHP对象数组 - 检查数组键是否存在

I have the following object array returned from a soap call:

$result = $this->soapClient->__soapCall($method, $arguments);

var_dump($result);


object(stdClass)#4 (1) {
    ["Jobs_GetResult"]=> object(stdClass)#5 (3) {
        ["Jobs"]=> array(4) {
              [0]=> object(stdClass)#7 (19) {
                    ["JobID"]=> int(55082846)
                    ["JobName"]=> string(18) "Fix xyz"
              } 

        }
        ["Errors"]=> object(stdClass)#10 (2) {
             ["Result"]=> int(0)
             ["Message"]=> string(0) "" 
        }
        ["RecordCount"]=> int(1) 
    }
}

I want to check if there are any errors - this is easy when the parent array key is known e.g:

if($result->Jobs_GetResult->Errors->Result > 0){
     // display message
}

The issue is I do not know what the name of the top level array key is going to be for most of the calls as i'm using a generic method - in the above example it's Jobs_GetResult so the above would work.

In instances where the top level array key is unknown how do I check if there are any errors returned?

In general the name of the parent array key is usually the name of the method call with Result appended to it. so I was thinking doing something along the lines of:

 if($result->$method . 'Result'->Errors->Result > 0){
     // display message
 }

But obviously the above syntax is incorrect. Any one know how to output value of $method and chain it to $result and append it with Result

Is there any other way I can check if the Errors array result is greater than 1 without knowing what the parent array key is?

  • 写回答

1条回答 默认 最新

  • du8442 2018-10-18 12:07
    关注

    Try this:

    $result = $this->soapClient->__soapCall($method, $arguments);
    
    $firstKey = key($result);
    
    if (!empty($firstKey) && !empty($result->{$firstKey}->Errors->Result)) {
        // display message
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里