简体   繁体   中英

foreach loop in a multidimensional array

Trying to get the a certain parameter in my multidimensional array... I have the following api request:

$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:

{
  "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. Right now, my code isn't showing anything.

You can do like this using 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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