使用PHP将字符串数据转换为数组
我必须将一长串数据转换为值,以便将它们导入数据库。不幸的是,数据显示为文本,而不是XML,因此我需要一种方法将其转换为键->值数组(理想情况下) 数据如下所示:使用PHP将字符串数据转换为数组,php,string,Php,String,我必须将一长串数据转换为值,以便将它们导入数据库。不幸的是,数据显示为文本,而不是XML,因此我需要一种方法将其转换为键->值数组(理想情况下) 数据如下所示: 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
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
经过研究,explode似乎是实现这一点的可行方法,但我不确定如何在这个场景中实现它,或者是否有更好的方法来实现这一点。特别是因为在字符串的中间可以有随机连字符和断线。
提前感谢您的帮助 由于值可以包含破折号并分布在多行中,我认为将键与值分离的最安全方法是使用
substr()
,因为分隔破折号始终位于字符串中的相同字符位置
固定的
<?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);
?>