drox90250557
drox90250557
2014-09-02 03:45
浏览 58
已采纳

在PHP中将文本文件转换为多维关联数组

I have this lab problem that I've now been stuck on for three days and I'm pretty sure after countless googling and trying pretty much everything I can find, that I've just confused myself to the point of being utterly lost. I'm not sure if this is what you guys do, but essentially I want the answer with a "how to" of how you got there. In my head I know what I want to do but just cannot fathom getting this into code.

To start, I have a text file, postcode.txt, with a list of postcodes and their respective suburbs like so:

3000,MELBOURNE
3001,MELBOURNE
3002,EAST MELBOURNE
3003,WEST MELBOURNE

This needs to be put into an array with the suburb names as the keys, and the postcodes as the values. As you can see, some suburbs have more than one postcode. Am I correct in thinking this will be a multi-dimensional associative array?

I'm not sure if it's best to use file() or file_get_contents() as I'm very new to PHP and have never even used an array before, let alone something this confusing. I can then assume I need to explode the lines of text by ',' and somehow have the suburbs as keys and the postcodes as values.

Once this is in an array I need to search this array by way of user input for a particular suburb name and it needs to return the value or values of that suburb. From the things that I have tried it isn't returning values at all so I can only assume it's something to do with case sensitivity or white spaces etc.

I'm not entirely sure why this is a lab question when I've yet to have any lab questions dealing with simple arrays, but nothing I can do except desperately try and understand this. It's been driving me mad. Any help is very much appreciated.

图片转代码服务由CSDN问答提供 功能建议

我有这个实验室问题,我现在已经坚持了三天而且我很确定无数次 谷歌搜索和尝试我能找到的所有东西,我只是把自己弄糊涂到完全失去的地步。 我不确定这是不是你们这样做的,但基本上我想要的答案是“如何”到达那里。 在我的脑海里,我知道自己想要做什么,但却无法理解我的代码。

首先,我有一个文本文件postcode.txt,里面有一个邮政编码列表和他们的邮件 像这样的郊区:

  3000,MELBOURNE 
3001,MELBOURNE 
3002,EAST MELBOURNE 
3003,WEST MELBOURNE 
   
 
  

这需要放入一个数组,其中郊区名称为键,邮政编码为值。 如您所见,一些郊区有多个邮政编码。 我认为这将是一个多维关联数组吗?

我不确定是否最好使用file()或file_get_contents(),因为我很新 PHP以前从未使用过数组,更不用说令人困惑的事了。 然后我可以假设我需要用','来爆炸文本行,并以某种方式将郊区作为键,将邮政编码作为值。

一旦这是一个数组我需要通过用户输入搜索特定郊区名称的数组,它需要返回该郊区的值。 从我尝试的事情来看,它根本不返回值,所以我只能假设它与区分大小写或空格等有关。

我不完全确定为什么 这是一个实验室问题,当我还没有任何关于简单数组的实验问题时,除了拼命尝试理解这一点之外我什么都做不了。 这让我很生气。 非常感谢任何帮助。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongwu9170
    dongwu9170 2014-09-02 04:13
    已采纳

    Reading your file

    To start with, opening the file... file() is the easiest method to read a file into an array as it is performed with one line.

    Drawbacks:

    • file() can be slow for larger files, as it needs to read the entire file into an array before you can use it

    Alternatively, use the standard file open structure using something like fgets() to read it line by line.

    Drawbacks:

    • more lines of code required

    Let's use file() as an example:

    $lines = file('postcodes.txt');
    

    Getting the array structure

    The first part of your question is how to get the array structure you want, which is the suburb name as the array key and all the post codes as the values. There are plenty of ways to do this - here's a simple example using a foreach:

    // Define an empty array to start with
    $postcodes = array();
    // Loop each line
    foreach($lines as $line) {
        // Split the line by the comma and define the variables with each part
        // mapping trim to the array to remove any whitespace on either end
        list($postcode, $suburb) = array_map('trim', explode(',', $line));
        // Check the array key exists in post codes
        if(!array_key_exists($suburb, $postcodes)) {
            // If not, define it to start with
            $postcodes[$suburb] = array();
        }
    
        // Check if the postcode is already in the array
        if(in_array($postcode, $postcodes[$suburb])) {
            // Skip this postcode, it's already where it should be
            continue;
        }
    
        // Add the postcode to it
        $postcodes[$suburb][] = $postcode;
    }
    

    Docs: array_map(), array_key_exists(), in_array(), explode(), foreach, continue

    An output of the resulting array would yield something like this:

    Array
    (
        [MELBOURNE] => Array
            (
                [0] => 3000
                [1] => 3001
            )
    
        [EAST MELBOURNE] => Array
            (
                [0] => 3002
            )
    
        [WEST MELBOURNE] => Array
            (
                [0] => 3003
            )
    
    )
    

    Searching the array

    Searching is a kettle of fish, and there are many things to consider. Do you want to return a case sensitive result, case insensitive, partial results, multiple results etc?

    Here are some options and what you should use for them:

    • Exact match (single): array_keys($postcodes, 'suburb name')
    • Exact match (multiple): wouldn't happen as you're using array keys (unique by definition)
    • Partial match (single): a loop, strstr() (case sensitive) or stristr() (case insensitive) matching the key and the search term and killing the loop if it is found
    • Partial match (multiple): same as above, but don't kill the loop if it's found, instead add to an array of matched results and return that

    Here's an example function to return all partially matches results from the array:

    function search($postcodes, $search_term) {
        // Define empty array for matches
        $matches = array();
        // Trim the search string to remove whitespace from either end
        $search_term = trim($search_term);
        // Loop through postcodes
        foreach($postcodes as $suburb => $post_codes) {
            // Case insensitive comparison
            if(stristr($suburb, $search_term)) {
                // It matches! Add entire result to return array
                $matches[$suburb] = $post_codes;
            }
        }
        // Return result
        return $matches; 
    }
    

    Example use:

    print_r($search($postcodes, 'melbourne'));
    print_r($search($postcodes, 'east'));
    
    Array
    (
        [MELBOURNE] => Array
            (
                [0] => 3000
                [1] => 3001
            )
    
        [EAST MELBOURNE] => Array
            (
                [0] => 3002
            )
    
        [WEST MELBOURNE] => Array
            (
                [0] => 3003
            )
    
    )
    Array
    (
        [EAST MELBOURNE] => Array
            (
                [0] => 3002
            )
    
    )
    

    Looking forward, you might also want to match any of the search terms passed in as a string, e.g. "east west" to match both east and west Melbourne. In this case you'll need to explode the search string to spaces, and perform a search on each term. You'll need to ensure to only return unique values here. Here's an example of a function that would do that:

    function search_multi($postcodes, $search_term) {
        // Define empty array for matches
        $matches = array();
        // Trim the search string
        $search_term = trim($search_term);
        // Get all search terms
        $search_terms = explode(' ', $search_term);
        // Loop through search terms
        foreach($search_terms as $term) {
            // Loop through postcodes
            foreach($postcodes as $suburb => $post_codes) {
                // First, check that this result hasn't already been found! (unique)
                if(array_key_exists($suburb, $matches)) {
                    // It's already been found, skip this one...
                    continue;
                }
                // Case insensitive comparison
                if(stristr($suburb, $term)) {
                    // It matches! Add entire result to return array
                    $matches[$suburb] = $post_codes;
                }
            }    
        }
        // Return result
        return $matches; 
    }
    

    And given you search for "east west", the result would be:

    Array
    (
        [EAST MELBOURNE] => Array
            (
                [0] => 3002
            )
    
        [WEST MELBOURNE] => Array
            (
                [0] => 3003
            )
    
    )
    

    Conclusion

    This kind of data structure would be best to be stored in a database if it's going to be used more than once, but to parse a text/CSV file this is how you'd approach it. Hope this helps.

    点赞 评论

相关推荐