【问题标题】:Response from ABAP webservice returns array for multiple items but returns an object for single item来自 ABAP Web 服务的响应返回多个项目的数组,但返回单个项目的对象
【发布时间】:2020-09-10 15:34:46
【问题描述】:

我正在运行一个 web 服务来连接到 ABAP 并在 PHP 上返回它。对于多个项目,它包含在对象数组中。但是如果它只有 1,它只是一个对象。

多个项目

+"TStockResponse": {#398
    +"item": array:3 [
      0 => {#399
        // item data here
      }
      1 => {#400
        // item data here
      }
      2 => {#401
        // item data here
      }
    ]
  }

与单个项目

+"TStockResponse": {#393
    +"item": {#387
      // item data here
    }
  }

想知道 PHP 上是否有一个选项来确定项目是否只有 1,它将它包含在一个数组中并继续执行必要的 foreach() 函数。


foreach($results->TStockResponse as $resp)
    {
         if(count($resp) == 1)
         {
              // do single task
         }
         else
         {
              foreach($resp as $res)
              {
                   // do each task
              }
         } 
    }

这是我当前的 PHP 代码,如果我尝试将单个项目发送到 ABAP,我会在 count() 上收到 ErrorException

【问题讨论】:

    标签: php


    【解决方案1】:

    应该很简单

    if ( !is_array( $results->TStockResponse->item ) ) {
      $results->TStockResponse->item = [ $results->TStockResponse->item ];
    }
    

    【讨论】:

    • 工作,谢谢。但是由于某种原因,我已将括号更改为 array()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-11
    • 1970-01-01
    相关资源
    最近更新 更多