我有邮政编码的文本文件导入到一个关联数组像这样的关键搜索:PHP - 通过关联数组
3000,MELBOURNE
3001,MELBOURNE
3002,EAST MELBOURNE
3003,WEST MELBOURNE
3004,MELBOURNE
...
8001,MELBOURNE
讲师曾说过,我们需要使用此加载到一个关联数组郊区名称为密钥和邮政编码为值。我已经做了关于如何做到这一点的研究,最好的我能想出是:
<?php
if(isset($_GET['suburbField'])) {
$userInput = $_GET['suburbField'];
//load the postcodes file into an array
$postcodes = file('postcode.txt');
//use an associative array - slides 51, 52
foreach ($postcodes as $lineNum => $line) {
//str split by comma and into new array - refer slide 17, 18
list($value, $key) = explode(",", $line);
$split_postcodes[rtrim($key)] = rtrim($value);
}
print_r($split_postcodes); //test that keys and vars assigned correctly
}
这给了这样的事情:
Array (
[MELBOURNE] => 8001,
[EAST MELBOURNE] => 8002,
[WEST MELBOURNE] => 3003
)
我需要什么才能够do是从输入框中获取郊区名称(我可以很容易地做到这一点),然后使用该字段搜索键并返回它的值。这对于一个独特的郊区名称非常适用,但在墨尔本这样的郊区有多个邮政编码时会下降。我已经使用了PHP功能array_key_exists
,但这只能给一个郊区。
我已经发现这是因为我的数组安装不正确。而不是存储多个值的关键墨尔本,它分配最后一个它看到=> 8001
有人可以帮我吗?我一直在这上面花费太长时间,这让我很难过。我需要它来显示这样的东西:
The postcode for MELBOURNE is 3000
The postcode for MELBOURNE is 3001
The postcode for MELBOURNE is 3004
The postcode for MELBOURNE is 8001
夫妇明显这里的东西。 '钥匙是唯一的'邮政编码是独特的,所以他们应该是钥匙。或者如果你必须数组(array(key => val)) – ron