doulan0297 2017-11-23 16:36
浏览 49
已采纳

从嵌套数组获取信息php

I am making calls to an API

I have the response as an associative array so that I can use:

$field = $response['nameOfKey'];

However, some of the values for keys are themselves arrays like the following:

{
  "Title": "Mr",
  "Forenames": "Steve",
  "Surname": "Williams",
  "CountryOfBirth": 1,
  "EmailAddress": "john.doe@email.com",
  "EmailType": "Personal",
  "BirthDate": "\/Date(632880000000)\/",
  "Suffix": null,
  "NationalInsuranceNumber": null,
  "PrimaryAddress": {
    "Address1": "Flat 1",
    "Address2": "Oxford Street",
    "City": "London",
    "County": "London",
    "Postcode": "L12456",
    "Country": 1
  },
  "AdditionalAddresses": [
    {
      "Address1": null,
      "Address2": null,
      "City": null,
      "County": null,
      "Postcode": null,
      "Country": 0,
      "AddressType": 0
    }
  ],
  "PrimaryTelephone": {
    "Number": "123456789",
    "DialingCode": 1,
    "TelephoneType": 1
  },
  "AdditionalTelephone": [
    {
      "Number": "223456789",
      "DialingCode": 2,
      "TelephoneType": 2
    }
  ],
  "BankAccount": {
    "AccountName": "John Doe Account",
    "AccountNumber": "123456789",
    "SortCode": "123456"
  },
  "PrimaryCitizenship": {
    "CountryOfResidency": 1,
    "TaxIdentificationNumber": "AB12CD34EF56"
  },
  "AdditionalCitizenship": [
    {
      "CountryOfResidency": 0,
      "TaxIdentificationNumber": null
    }
  ],
  "ExternalCustomerId": "91",
  "ExternalPlanId": "91",
  "PlanType": 10
}

So at the moment to get Forename I can just do $forename = $decodedResponse["Forenames"]; but I'm quite baffled at trying to get values from the inner arrays.

I thought I could do something like this:

foreach($decodedResponse as $data)
        {
            foreach($data['TelephoneNumbers'] as $tel)
            {
                echo $tel['Number']; die();
            }
}

Essentially loop through the original Associative array and then loop through a specific key to get its values.

  • 写回答

1条回答 默认 最新

  • doubaisui2526 2017-11-23 16:40
    关注

    Your should use foreach for following array items: AdditionalAddresses, AdditionalTelephone and AdditionalCitizenship. Otherwise just chain array keys. See examples:

    $forename = $decodedResponse['Forenames'];
    $address2 = $decodedResponse['PrimaryAddress']['Address2'];
    
    foreach ($decodedResponse['AdditionalTelephone'] as $tel) {
      echo $tel['Number'];
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 无源定位系统的时差估计误差标准差
  • ¥15 请问这个代码哪里有问题啊
  • ¥20 python--version在命令端输入结果Python is not defined怎么办?还有pip不是exe格式是不是没安装成功?
  • ¥15 通过GaussianView进行结构微调消除虚频
  • ¥15 调用transformers库
  • ¥15 由于导出的数据名字中带有/,导致Matlab打不开,怎么办?
  • ¥15 新硬盘安装的程序总是崩溃,提示遇到错误
  • ¥15 openpcdet自制数据集评估bev精度和3d精度相同
  • ¥15 excel 上下按钮 显示行
  • ¥20 云卓h12pro 数传问题