我有一个这种格式的文本文件,我希望将其转换为格式化后的数组。
文本文件内容:
Header = "This is header"
Object class = "First"
min_size = 0
max_size = 727.555
content= true
size = 1
item []:
item [1]:
class = "Convert"
name = "CONTENT"
min_size = 0
max_size = 727.555
intervals: size = 474
intervals [1]:
min_size = 0
max_size = 13.139997023062838
type = ""
intervals [2]:
min_size = 13.139997023062838
max_size = 14.763036269953904
type = "this is a type"
intervals [3]:
min_size = 14.763036269953904
max_size = 17.01
type = ""
intervals [4]:
min_size = 17.01
max_size = 18.193
type = ""
如果可能,我想将其转换为类似的数组:
Array
(
[1] =>
Array(
['min_size'] = 0,
['max_size'] = 13.139997023062838,
['type'] = ""
)
[2] =>
Array(
['min_size'] = 13.139997023062838,
['max_size'] = 14.763036269953904,
['type'] = "this is a type"
)
我已经尝试过这样的事情:
$file = "array.txt";// Your Temp Uploaded file
$cols = array();
ini_set('auto_detect_line_endings', true);
$fh = fopen($file, 'r');
$i = 0;
while (($line = fgetcsv($fh, 1000, "\t")) !== false) {
$cols[] = $line;
}
echo "<pre>";
print_r($cols);
echo "</pre>";
但这只会把所有东西都变成一个阵列。
这可能吗?
答案 0 :(得分:1)
包含preg_match_all
,array_map
和array_combine
函数的复杂解决方案:
$data = file_get_contents('array.txt');
$pat = '/intervals \[\d+\]:\s+\Kmin_size = (?P<min_size>\d+(\.\d+)?) \
\s+max_size = (?P<max_size>\d+(\.\d+)?)\s+type = "(?P<type>[^"]*)"/m';
preg_match_all($pat, $data, $m);
$result = array_map(function($a){
return array_combine(['min_size', 'max_size', 'type'], $a);
}, array_map(null, $m['min_size'], $m['max_size'], $m['type']));
print_r($result);
输出:
Array
(
[0] => Array
(
[min_size] => 0
[max_size] => 13.139997023062838
[type] =>
)
[1] => Array
(
[min_size] => 13.139997023062838
[max_size] => 14.763036269953904
[type] => this is a type
)
[2] => Array
(
[min_size] => 14.763036269953904
[max_size] => 17.01
[type] =>
)
[3] => Array
(
[min_size] => 17.01
[max_size] => 18.193
[type] =>
)
)