是否可以在php中转换此类数据
ABANO TERME A001
ABBADIA CERRETO A004
ABBADIA LARIANA A005
ABBADIA SAN SALVATORE A006
ABBASANTA A007
ABBATEGGIO A008
ABBIATEGRASSO A010
到一个关联的数组,其中第一列是键,第二列是值?
答案 0 :(得分:2)
$handle = fopen(path\to\file\filename, "r");
$result_arr = array();
while(($filesop = fgets($handle)) !== false)
{
$line_arr = explode(" ", $filesop);
$value = end($line_arr);
unset($line_arr[array_search($value, $line_arr)]);
$key = implode(" ", $line_arr);
$result_arr[trim($key] = trim($value);
}
print_r($result_arr);
像这样存储在文本文件中(以逗号分隔):
ABANO TERME,A001
ABBADIA CERRETO,A004
ABBADIA LARIANA,A005
ABBADIA SAN SALVATORE,A006
ABBASANTA,A007
ABBATEGGIO,A008
ABBIATEGRASSO,A010
读取文件的解决方案:
$handle = fopen(path\to\file\filename, "r");
$result_arr = array();
while(($filesop = fgets($handle)) !== false)
{
$line_arr = explode(",", $filesop);
$value = end($line_arr);
unset($line_arr[array_search($value, $line_arr)]);
$key = implode(",", $line_arr);
$result_arr[trim($key] = trim($value);
}
print_r($result_arr);
答案 1 :(得分:2)
$txt = file_get_contents('foo.txt');
$arr=array_values(array_filter(explode(' ',$txt)));
$new=[];
for($i=0; $i<count($arr)-1;$i++){
$new[$arr[$i]]=$arr[++$i];
}
print_r($new);
答案 2 :(得分:1)
这个特定数据的一个解决方案是:
<?php
$data = file_get_contents('data.txt')
//use regular expressions to parse whole file at once
preg_match_all("/([^\s]+\s?[^\s]+?)\s+(.\d+)$/m", $data, $m);
//and combine results from result array ($m)
//first entry - $m[0] contains whole lines thats why I dont use it here
//second entry - $m[1] - data from first brackets is an array key
//third entry - $m[2] - is a value (both are separated by some number of spaces - \s+)
$array = array_combine($m[1], $m[2]);
print_r($array);
?>
输出:
Array
(
[ABETONE] => A012
[ABRIOLA] => A013
[ACATE] => A014
[ACCADIA] => A015
)
当然,正如上面的同事所指出的,这取决于数据的来源,以及这个特定的集合是否具有代表性。