2011-11-07 23 views
1

我必須將長數據串轉換爲值才能將它們導入到我的數據庫中。不幸的是,數據顯示爲文本而不是XML,所以我需要一種方法將其轉換爲理想的鍵 - 值數組。使用PHP將數據字符串轉換爲數組

的數據是這樣的:

AU - Author 1 
AU - Author 2 
AU - Author 3 
LA - ENG 
PT - ARTICLE 
DEP - 235234 
TA - TA 
JN - Journal name 
JID - 3456346 
EDAT- 2011-11-03 06:00 
MHDA- 2011-11-03 06:00 
CRDT- 2011-11-03 06:00 
TI - multi-line text text text text text 
     text text tex tex text 
     text text tex tex text 

研究後,好像爆炸可能是實現這一目標的可行手段,但我不知道如何實現它在此之情況,或者如果有是一個更好的方法來完成這一點。特別是因爲在字符串中間可能會出現隨機連字符和換行符。

任何幫助提前感謝!

回答

3

因爲值可以包含破折號並分佈在多行中,所以我認爲用鍵分隔鍵最安全的方法是使用substr(),因爲分隔破折號始終位於字符串中的相同字符位置。

FIXED

<?php 

    // first, split into lines 
    $lines = explode("\n",str_replace(array("\r\n","\r"),"\n",$data)); 

    // this will hold the parsed data 
    $result = array(); 

    // This will track the current key for multi-line values 
    $thisKey = ''; 

    // Loop the split data 
    foreach ($lines as $line) { 
    if (substr($line,4,1) == '-') { 
     // There is a separator, start a new key 
     $thisKey = trim(substr($line,0,4)); 
     if ($result[$thisKey]) { 
     // This is a duplicate value 
     if (is_array($result[$thisKey])) { 
      // already an array 
      $result[$thisKey][] = trim(substr($line,5)); 
     } else { 
      // convert to array 
      $result[$thisKey] = array($result[$thisKey],trim(substr($line,5))); 
     } 
     } else { 
     // Not a duplicate value 
     $result[$thisKey] = trim(substr($line,5)); 
     } 
    } else { 
     // There is no separator, append data to the last key 
     if (is_array($result[$thisKey])) { 
     $result[$thisKey][count($result[$thisKey]) - 1] .= PHP_EOL.trim(substr($line,5)); 
     } else { 
     $result[$thisKey] .= PHP_EOL.trim(substr($line,5)); 
     } 
    } 
    } 

    print_r($result); 

?> 

See it working

+0

戴夫,你是男人。非常感謝! – skiindude22