2012-07-26 60 views
-2

如何可以轉換條目從.dict文件,如:轉換.dict到陣列

aveu 
    acknowledgement, admission 

到PHP數組等

$陣列[ 'aveu'] = array(1 =>'acknowledgement',2 =>'admission');

感謝您的幫助!

回答

0

假設父代在它之前沒有空格,並且子記錄以空白開始以逗號分隔,則循環遍歷文件中的行。如果前面沒有空格(通過preg_match()),請啓動一個新的數組鍵和後續的空白行。

$output = array(); 
$lines = file('yourfile.dict'); 
foreach ($lines as $line) { 
    // Skip blank lines 
    if (strlen(trim($line)) > 0) { 
    // No leading whitespace, start a new key: 
    if (!preg_match('/^\s+/', $line)) { 
     $key = trim($line); 
     $output[$key] = array(); 
    } 
    // Otherwise, explode and add to the previous $key (if $key is non-empty) 
    else if (!empty($key)) { 
     $terms = explode(",", $line); 
     // Trim off whitespace 
     $terms = array_map('trim', $terms); 
     // Merge them onto the existing key (if multiple lines) 
     $output[$key] = array_merge($output[$key], $terms); 
    } 
    else { 
     // Error - no current $key 
     echo "??? We don't have an active key."; 
    } 
    } 
}