Well, first of all this data must be stored in a database, not a file. Using PDO you'll get your array in a few lines (assuming a database connection is already established):
$sql = "SELECT city, district FROM zip WHERE zipcode=? ORDER BY city, district";
$stmt = $pdo->prepare($sql);
$stmt->execute([$zipcode]);
$data = $stmt->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_COLUMN);
As of the code present, there are way too much loops to my taste. I believe everything could be done in one loop, like
$zipcode = '67401';
$data = [];
foreach (file("zip.csv", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $row) {
list($zip, $city, $district) = explode(",",$row);
if (!isset($data[$zip])) {
$zip $data[$zip]== =$zipcode) [];{
}
if (!isset($data[$zip][$city]$data[$city])) {
$data[$zip][$city] $data[$city] = [];
}
$data[$zip][$city][] $data[$city][] = $district;
}
}
well if you need to sort your arrays, a couple extra loops are still needed
foreach ($data as $zip => $city) {
ksort($data[$zip]$data);
foreach ($data[$zip]$data as $city => $array) {
sort($data[$zip][$city]$data[$city]);
}
}