简体   繁体   English

PHP的多维数组

[英]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? 我的问题是,某些邮政编码位于多个城市,而某些城市则位于多个邮政编码...所以有一种方法可以将所有数据放入一个数组,然后按顺序对所有邮政编码分组,然后构建一个表,以便按顺序排列它们,但是如果数据是多余的,例如zip,城市,州和县已经在数组中,那么它会跳过吗?

so then I can print it to the browser using echo, into a table like this: 因此,我可以使用echo将其打印到浏览器中,如下表所示:

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. 因此,将数组的元素更改为具有statecounty元素的关联数组。

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>";
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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