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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改