基本上我有这样一个数组:
$data = array(
'aaa' => "moo moo\n",
'bbb' => "quack quack\n",
'ccc' => "bark bark\n",
...);
然后有一个这样的文本文件:
field1 value1
field2 value2
field-id aaa
field1 value1
field-id ccc
field3 value3
...
文本文件中的空白行表示记录分隔符。当数组键与记录的field-id
的值匹配时,我需要在记录的底部注入数组值。因此,上述示例的文本文件将变为:
field1 value1
field2 value2
field-id aaa
moo moo
field1 value1
field-id ccc
field3 value3
bark bark
...
答案 0 :(得分:1)
通常您会按照以下步骤操作:
答案 1 :(得分:0)
作为快速草稿,我会尝试这样的事情:
// read in textfile
$f = file_get_contents('something.txt');
// turn it into an array by separating at empty lines
$f = preg_split('/^ *$/', $f);
// get search strings as an array
$k = array_keys($data);
// loop over the datasets from textfile
foreach($f as $ff) {
// search current dataset with search strings until found
foreach($k as $kk){
if(strpos($ff, $kk) !== false){
// if searchstring found, append data to dataset
$ff .= "\n" . $data[$kk];
break;
}
}
// append dataset to output whether modified or not
$out .= $ff . "\n" ;
}
// overwrite the textfile with the modified version
file_put_contents('something.txt');
这是未经过测试,但应该提供一个起点。