简体   繁体   English

PHP - 按关联数组键搜索

[英]PHP - Searching by Key of associative array

I have a text file of postcodes to import into an associative array like this: 我有一个文本文件的邮政编码导入到一个关联数组,如下所示:

3000,MELBOURNE
3001,MELBOURNE
3002,EAST MELBOURNE
3003,WEST MELBOURNE
3004,MELBOURNE
...
8001,MELBOURNE

The lecturer has said that we need to load this into an associative array using the suburb name as the key and the postcode as the value . 讲师说我们需要使用郊区名称作为键并将邮政编码作为值将其加载到关联数组中。 I've done a bit of research on how to do this and the best I could come up with was : 我已经做了一些关于如何做到这一点的研究,我能想到的最好的是:

<?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
    }

This gives something like this: 这给出了这样的东西:

Array (
 [MELBOURNE] => 8001,
 [EAST MELBOURNE] => 8002,
 [WEST MELBOURNE] => 3003
)

What I need to be able to do is GET a suburb name from an input box (I can do this easily enough), then use that field to search the keys and return it's value. 我需要做的是从输入框中获取一个郊区名称(我可以很容易地做到这一点),然后使用该字段搜索键并返回它的值。 This works great for a unique suburb name, but falls down when there are multiple postcodes for the one suburb like Melbourne. 这对于一个独特的郊区名称非常有用,但是当像墨尔本这样的一个郊区有多个邮政编码时,它就会倒下。 I've used the PHP function array_key_exists , but this only gives the one suburb. 我已经使用了PHP函数array_key_exists ,但这只给了一个郊区。

I've since found out that this is because my array isn't setup correctly. 我发现这是因为我的阵列设置不正确。 Instead of storing multiple values for key MELBOURNE , it is assigning the last one it sees => 8001 它不是为密钥MELBOURNE存储多个值,而是分配它看到的最后一个=> 8001

Can someone please help me? 有人可以帮帮我吗? I've been spending too long on this and it is killing me. 我花了太长时间在这上面,它正在杀了我。 I need it to display something like: 我需要它来显示如下内容:

The postcode for MELBOURNE is 3000
The postcode for MELBOURNE is 3001
The postcode for MELBOURNE is 3004
The postcode for MELBOURNE is 8001

To "search" by a key, you need only use the key. 要通过密钥“搜索”,您只需使用密钥。

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

Of course, if that key doesn't exist in the array, you'll get an error, so you would first want to check: 当然,如果数组中不存在该键,则会出现错误,因此您首先要检查:

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

If you want to return partial matches, something like this: 如果要返回部分匹配,请执行以下操作:

$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
    }
}

As you have a situation where one suburb can have more than one postcode you need to store the data as an array within an array, using the suburb as the key to the outer array. 由于您遇到一个郊区可能有多个邮政编码的情况,您需要将数据作为数组存储在数组中,使用郊区作为外部数组的键。

Like so:- 像这样: -

<?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';
}

The output from this would be 这样的输出就是

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

So, what you need is some way to store multiple values in a single slot. 因此,您需要的是在单个插槽中存储多个值的某种方式。 You already know how to do this; 你已经知道怎么做了; after all, you're using an array to store multiple lines in the $postcodes "slot". 毕竟,您正在使用数组在$postcodes “slot”中存储多行。

Read up on how arrays work , paying special attention to the $array[] = <expression> syntax. 阅读数组如何工作 ,特别注意$array[] = <expression>语法。 Once you've done that, you will need to modify the code that prints out your result. 完成后,您需要修改打印出结果的代码。 (Can you see how and why?) (你能看到怎么做以及为什么?)

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

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