简体   繁体   中英

php multi dimensional array's

I am pulling data out of a table that has these fields:

zipcode,city,state,county

My question is that some zip codes are in multiple cities, and some cities are in multiple zip codes... so is there a way to have all the data put into an array, then group all of the zip codes in order, then build a table out of that, so that it puts them in order, but if the data is redundant, like the zip, city, state and county are already in the array, then it skips it?

so then I can print it to the browser using echo, into a table like this:

74801 | Shawnee, Oklahoma | Pottawatomie
74801 | Bethel, Oklahoma | Pottawatomie
74801 | Johnson, Oklahoma | Pottawatomie
74851 | McLoud, Oklahoma | Pottawatomie
74851 | Dale, Oklahoma | Pottawatomie

etc. But in the case of these:

74015 | CATOOSA, Oklahoma | Rogers
74015 | COTOOSA, Oklahoma | Rogers

Because those are duplicates in those fields (not in the rest of the table), I need it to skip showing it twice.

I think it is something like this:

$zipArray = array();
$zipCode = $dbhhandle->zip;
$cityName = $dbhhandle->city;
$countyName = $dbhhandle->county;
if($zipArray[$zipCode][$cityName] != $countyName) {
   $zipArray[$zipCode][$cityName] = $countyName;
}

but I'm not sure if that is the right way to do it.

Then once I have the array built, how do I build the table?

Your code looks pretty close, but it's missing the state. So change the elements of the array into associative arrays with state and county elements.

Also, you need to check whether there's an entry for the zip code at all, before checking whether it's a duplicate, otherwise you'll access an undefined index.

$zipArray = array();
$zipCode = $dbhhandle->zip;
$cityName = $dbhhandle->city;
$countyName = $dbhhandle->county;
$stateName = $dbhandle->state;
if(!isset($zipArray[$zipCode][$cityName]) || $zipArray[$zipCode][$cityName]['county'] != $countyName) {
   $zipArray[$zipCode][$cityName] = array('county' => $countyName, 'state' => $stateName);
}

To display the table, you use nested loops.

foreach ($zipArray as $zip => $cities) {
    foreach ($cities as $city => $cityData) {
        echo "<tr><td>$zip</td><td>$city, {$cityData['state']}</td><td>{$cityData['county']}</td></tr>";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM