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 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 vue2登录调用后端接口如何实现