簡體   English   中英

在PHP中將文本文件轉換為多維關聯數組

[英]Converting text file into multi-dimensional associative array in PHP

我遇到了這個實驗室問題,現在已經堅持了三天,並且可以肯定的是,經過無數次谷歌搜索和嘗試了幾乎所有可以找到的一切之后,我確信自己已經迷失了自己,完全迷失了自己。 我不確定這是否是你們的工作,但從本質上講,我希望答案是“如何”到達那里的。 在我的腦海里,我知道我想做什么,但無法理解將其納入代碼中。

首先,我有一個文本文件postcode.txt,其中包含郵政編碼列表及其各自的郊區,如下所示:

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

這需要放入一個以郊區名稱為鍵,以郵政編碼為值的數組。 如您所見,有些郊區有多個郵政編碼。 我認為這將是一個多維關聯數組,對嗎?

我不確定是否最好使用file()或file_get_contents(),因為我對PHP還是很陌生,甚至從未使用過數組,更不用說這令人困惑了。 然后,我可以假設我需要用','分隔文本行,並以某種方式將郊區作為鍵,將郵政編碼作為值。

將其放入數組后,我需要通過用戶輸入在該數組中搜索特定的郊區名稱,並且它需要返回該郊區的一個或多個值。 從我嘗試過的東西來看,它根本沒有返回任何值,因此我只能認為這與區分大小寫或空格等有關。

當我還沒有處理簡單數組的任何實驗室問題時,我不能完全確定為什么這是一個實驗室問題,但是我無能為力,除非拼命嘗試理解這一點。 這讓我發瘋了。 很感謝任何形式的幫助。

讀取文件

首先,打開文件... file()是將文件讀入數組的最簡單方法,因為它只用一行執行。

缺點:

  • 對於較大的文件, file()可能會變慢,因為在使用它之前,它需要將整個文件讀入數組

或者,使用標准文件打開結構fgets()fgets()逐行讀取它。

缺點:

  • 需要更多代碼行

讓我們以file()為例:

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

獲取數組結構

問題的第一部分是如何獲取所需的數組結構,以郊區名稱作為數組鍵,將所有郵政編碼作為值。 有很多方法可以做到這一點-這是一個使用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;
}

文件: array_map()array_key_exists()in_array()explode()foreachcontinue

結果數組的輸出將產生如下內容:

Array
(
    [MELBOURNE] => Array
        (
            [0] => 3000
            [1] => 3001
        )

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

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

)

搜索數組

搜索是一鍋魚,有很多事情要考慮。 您是否要返回區分大小寫的結果,不區分大小寫的結果,部分結果,多個結果等?

以下是一些選項以及應使用的選項:

  • 完全匹配(單個): array_keys($postcodes, 'suburb name')
  • 完全匹配(多個):使用數組鍵時不會發生(按定義唯一)
  • 部分匹配(單個):循環,匹配stristr()和搜索詞的strstr() (區分大小寫)或stristr() (不區分大小寫),如果找到則終止循環
  • 部分匹配(多個):與上面相同,但不要殺死找到的循環,而要添加到匹配結果數組中並返回

這是一個示例函數,用於返回數組中所有部分匹配的結果:

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

使用示例:

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
        )

)

展望未來,您可能還想匹配以字符串形式傳遞的任何搜索詞,例如“ east west”以匹配墨爾本的東西方。 在這種情況下,您需要將搜索字符串分解為空格,然后對每個術語進行搜索。 您需要確保此處僅返回唯一值。 這是一個可以做到這一點的函數的例子:

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

並給您搜索“東西”,結果將是:

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

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

)

結論

如果要多次使用這種數據結構,最好將其存儲在數據庫中,但是要解析文本/ CSV文件,這就是您要采用的方法。 希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM