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 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退