Jesse Luke Orange
Jesse Luke Orange

Reputation: 1999

Getting information from nested arrays 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": "[email protected]",
  "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.

Upvotes: 0

Views: 29

Answers (1)

Jirka Hrazdil
Jirka Hrazdil

Reputation: 4021

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'];
}

Upvotes: 1

Related Questions