首页 > 解决方案 > 来自 ABAP 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

解决方案


应该很简单

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

推荐阅读