I am creating a contact form, which needs to change the sendto address based on an entered postal code.
I have an array of postal codes which I can search through, so that I know if the postal code entered is actually in the array.
Here's how I search through the array:
$districts = [
'district' => [
[
'name' => 'District A',
'email' => 'abc@example.com',
'url' => 'district-a',
'postalcodes' => [
'3311AA',
'3311AB',
],
],
[
'name' => 'District B',
'email' => 'xyz@example.com',
'url' => 'district-b',
'postalcodes' => [
'3317EA',
'3317EB',
'3317EC',
],
],
],
];
$results = array_filter($districts['district'], function($district) {
$key = array_search('3311AB', $district['postalcodes']);
return $key;
});
var_dump($results);
Now I need to return the email address, based on in which district the postal code is found.
How would I search for, for example, postal code 3311AB
and return the email address of the district to which it belongs?
Instead of returning key of postal code, you need to return $district['email']
$emails = [];
foreach ($districts['district'] as $district) {
if (in_array('3311AB', $district['postalcodes'])) {
$emails[] = $district['email'];
}
}
var_dump($emails);