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

관련 문제