Skip to content

Instantly share code, notes, and snippets.

@paul121
Created February 19, 2025 20:48
Show Gist options
  • Save paul121/04c0bcf66c46bc1b0d380febb70ceb0c to your computer and use it in GitHub Desktop.
Save paul121/04c0bcf66c46bc1b0d380febb70ceb0c to your computer and use it in GitHub Desktop.
State county mapping
<?php
// Path to your CSV file.
$csvFile = __DIR__ . '/usda.csv';
$stateCountyMapping = [];
// Read the CSV file.
if (($handle = fopen($csvFile, 'r')) !== false) {
// Skip the header row.
fgetcsv($handle);
// Process each row.
while (($row = fgetcsv($handle)) !== false) {
if (count($row) < 2) {
continue; // Skip invalid rows.
}
$state = $row[0];
$county = $row[1];
// Group counties by state.
if (!isset($stateCountyMapping[$state])) {
$stateCountyMapping[$state] = [];
}
$stateCountyMapping[$state][] = $county;
}
fclose($handle);
}
// Print the array as PHP code.
foreach ($stateCountyMapping as $state => $counties) {
echo " '$state' => [\n";
foreach ($counties as $county) {
echo " '$county',\n";
}
echo " ],\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment