【发布时间】:2014-03-31 23:46:57
【问题描述】:
我有一个邮政编码文本文件要导入到这样的关联数组中:
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
)
我需要做的是从输入框中获取郊区名称(我可以很容易地做到这一点),然后使用该字段搜索键并返回它的值。这对于一个独特的郊区名称非常有用,但当像墨尔本这样的一个郊区有多个邮政编码时,它就会失败。我使用了 PHP 函数array_key_exists,但这仅给出了一个郊区。
我后来发现这是因为我的阵列设置不正确。它没有为键 MELBOURNE 存储多个值,而是分配它看到的最后一个值 => 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(array(key=>val))
标签: php arrays associative-array