2011-11-07 48 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