简体   繁体   English

多维数组中的foreach循环

[英]foreach loop in a multidimensional array

Trying to get the a certain parameter in my multidimensional array... I have the following api request:试图在我的多维数组中获取某个参数......我有以下 api 请求:

$responeAPI= ClientCode::request('post', 'responeAPI', $responeAPI,['debug'=>true]); 

     foreach ($responeAPI["buDetail"] as $key => $value){
               $businessUserDet =  $value["name"];
     }

     $storage['enterpriseList'] = $businessUserDet;
    }

The array from the API response is like this: API 响应中的数组如下所示:

{
  "buList": {
    "buDetail": [
      {
        "businessUserId": 2,
        "name": "SAMPLENAME_231",
        "parentBusinessUserId": 1,
        "profileId": 2,
        "profileName": "Enterprise"
      }
    ]
  },
  "resultCode": 0,
  "transactionId": "responeAPIs_1577358460"
}

I need to extract the "name" so I can use it for the $options parameter.我需要提取“名称”,以便将其用于 $options 参数。 Right now, my code isn't showing anything.现在,我的代码没有显示任何内容。

You can do like this using array_column你可以这样做使用array_column

$jsonArray = '{"buList":{"buDetail":[{"businessUserId":2,"name":"SAMPLENAME_231","parentBusinessUserId":1,"profileId":2,"profileName":"Enterprise"},{"businessUserId":2,"name":"SAMPLENAME_231","parentBusinessUserId":1,"profileId":2,"profileName":"Enterprise"}]},"resultCode":0,"transactionId":"responeAPIs_1577358460"}';

   $detais = json_decode($jsonArray, true);

   print_r(array_column($detais['buList']['buDetail'], 'name', 'id'));

http://sandbox.onlinephpfunctions.com/code/458592622c78c67771cbf2e54661b9294c91e710 http://sandbox.onlinephpfunctions.com/code/458592622c78c67771cbf2e54661b9294c91e710

Could you change this line你能改变这一行吗

foreach ($responeAPI["buDetail"] as $key => $value){

to

foreach ($responeAPI["buList"]["buDetail"] as $key => $value){

You can invoke as an object:您可以作为对象调用:

$array = '{ "buList": { "buDetail": [{ "businessUserId": 2, "name": "SAMPLENAME_231", "parentBusinessUserId": 1, "profileId": 2, "profileName": "Enterprise" } ] }, "resultCode": 0, "transactionId": "responeAPIs_1577358460" }';
$array = json_decode($array);
//for debug purposes only
echo var_export($array, true);
echo $array->buList->buDetail[0]->name;

Output: SAMPLENAME_231输出: SAMPLENAME_231

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM