PHP - 按关联数组的键搜索


PHP - Searching by Key of associative array

我有一个邮政编码的文本文件,可以导入到一个关联数组中,如下所示:

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
)

我需要做的是从输入框中获取一个郊区名称(我可以很容易地做到这一点),然后使用该字段搜索键并返回其值。这适用于唯一的郊区名称,但当像墨尔本这样的一个郊区有多个邮政编码时,就会下降。我已经array_key_exists使用了PHP函数,但这只给出了一个郊区。

从那以后,我发现这是因为我的阵列设置不正确。它不是为密钥墨尔本存储多个值,而是分配它看到的最后一个值=> 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

由于您遇到一个郊区可以有多个邮政编码的情况,您需要将数据存储为数组中的数组,使用郊区作为外部数组的键。

这样:-

<?php
$postcodes = file('postcodes.txt');
foreach ($postcodes as $line) {
    list($po, $burb) = explode(",", $line);
    $burb = str_replace(PHP_EOL, '', $burb);
    $pcodes[$burb][] = $po;
}
print_r($pcodes);
$userInput = 'MELBOURNE';
if ( array_key_exists($userInput, $pcodes) ) {
    foreach ( $pcodes[$userInput] as $oneOfTheCodes ) {
        echo 'The postcode for ' . $userInput . ' is ' . $oneOfTheCodes . PHP_EOL;
    }
} else {
    echo 'Suburb does not exist';
}

由此产生的输出将是

Array
(
    [MELBOURNE] => Array
        (
            [0] => 3000
            [1] => 3001
            [2] => 3004
            [3] => 8001
        )
    [EAST MELBOURNE] => Array
        (
            [0] => 3002
        )
    [WEST MELBOURNE] => Array
        (
            [0] => 3003
        )
)
The postcode for MELBOURNE is 3000
The postcode for MELBOURNE is 3001
The postcode for MELBOURNE is 3004
The postcode for MELBOURNE is 8001

要按键"搜索",您只需使用该键。

$postcode = $suburbs['EAST MELBOURNE'];

当然,如果数组中不存在该键,则会收到错误,因此您首先要检查:

if(isset($suburbs['EAST MELBOURNE'])) {
    // blah
}

如果要返回部分匹配项,如下所示:

$search = $_GET['suburb'];  // get the desired search query from GET
foreach($suburbs as $suburb => $postcode) // loop through each suburb, naming the key 'suburb' and the value 'postcode'
{
    if(stristr($suburb, $search)) // if the search string exists within the current suburb
    {
        echo "The postcode for $search is $postcode<br>"; // echo out the line
    }
}

因此,您需要的是某种在单个插槽中存储多个值的方法。您已经知道如何执行此操作;毕竟,您正在使用数组在$postcodes"插槽"中存储多行。

阅读数组的工作原理,特别注意$array[] = <expression>语法。完成此操作后,您将需要修改打印结果的代码。(你能看到如何以及为什么吗?