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 深度学习残差模块模型
  • ¥20 两个不同Subnet的点对点连接
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)