I've got a .csv file with ZIP codes containing the city and its sub-districts
67401,City 1,district_a 67401,City 2,district_b 67401,City 3,district_c 67401,City 3,district_d 67401,City 3,district_e 67401,City 3,district_f 67401,City 3,district_g 67401,City 3,district_h 67401,City 3,district_i 67401,City 3,district_j 67401,City 3,district_k 67401,City 3,district_l 67401,City 3,district_m 67401,City 3,district_n 67401,City 3,district_o 67401,City 3,district_p 67401,City 3,district_q 67401,City 3,district_r 67401,City 3,district_s 67401,City 4,district_t 67401,City 5,district_u 67501,City 6,district_v 67501,City 7,district_w 67501,City 8,district_x 67501,City 8,district_y 67501,City 8,district_z
And I need to put it in an array, where I can select/search by the zip code (67401, 67501, etc.) and return these results as an associative array in this format, so I can populate a select control.
For example I want to look-up all the Cities and its districts with zip code 67401 I need this result:
"City 1" => [
district_a => district_a
],
"City 2" => [
district_b => district_b
],
"City 3" => [
district_c => district_c
district_d => district_d
district_e => district_e
district_f => district_f
district_g => district_g
district_h => district_h
district_i => district_i
district_j => district_j
district_k => district_k
district_l => district_l
district_m => district_m
district_n => district_n
district_o => district_o
district_p => district_p
district_q => district_q
district_r => district_r
district_s => district_s
],
"City 4" => [
district_t => district_t
],
"City 5" = [
district_u => district_u
]
Right now I've got this working code, but I'm sure there has to be a simpler way to achieve it.
<?php
$zipcode = '67401';
$a = file("zip.csv", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$a = array_map(function ($i) {return explode(',', $i); }, $a);
$a = array_filter($a, function ($i) use ($zipcode) { return $i[0] == $zipcode; });
$b = [];
$i = 0;
foreach ($a as $key => $value) {
$b[$i++] = [
'city' => $value[1],
'district' => $value[2],
];
}
$c = [];
foreach($b as $key => $item) {
$c[$item['city']][$key] = $item;
}
ksort($c, SORT_REGULAR);
$d = [];
foreach($c as $key => $value) {
$subarray = [];
foreach($value as $s_key => $s_val) {
foreach($s_val as $ss_key => $ss_val) {
$subarray[$ss_val] = $ss_val;
}
}
$d[$key] = $subarray;
}
$myresult = $d;
?>