我为这个问题写了一个函数:
<?php
$array = parse_my_file("file.txt");
print_r($array);
function parse_my_file($file){
if(file_exists($file)){
$data = file_get_contents($file);
$class = explode("class ", $data);
unset($class[0]);
$class_sanitized = array_map(function($v){
$temp = explode(PHP_EOL . "{" . PHP_EOL, substr($v, 0, -4), 2);
$temp[1] = array_filter(explode(PHP_EOL, $temp[1]));
$temp[1] = array_map(function($w){
$value = explode("=", trim(substr($w, 0,-1), " "));
return($value);
}, $temp[1]);
return($temp);
}, $class);
$return_array = array();
foreach($class_sanitized as $value){
$return_array[$value[0]] = array_map(function($z){
if(substr($z[1], 0, 1) == '"' AND substr($z[1], -1) == '"'){
$z[1] = substr($z[1], 1, -1);
}
return(array($z[0] => $z[1]));
}, $value[1]);
}
return $return_array;
}else{
return array("Deze bestand bestaat niet");
}
}
?>
输出是:
Array
(
[Thing1] => Array
(
[0] => Array
(
[pos[]] => {120.03,121,134.0987}
)
[1] => Array
(
[heading] => -92.049
)
[2] => Array
(
[anotherthing] => 19
)
[3] => Array
(
[foo] => thing
)
[4] => Array
(
[kind] => This_item
)
[5] => Array
(
[foo] => 0.293333
)
[6] => Array
(
[foo] => this thing
)
)
[Thing2] => Array
(
[0] => Array
(
[pos[]] => {220.03,221,234.0987}
)
[1] => Array
(
[heading] => -292.049
)
[2] => Array
(
[anotherthing] => 219
)
[3] => Array
(
[foo] => thing2
)
[4] => Array
(
[kind] => This_item2
)
[5] => Array
(
[foo] => 2.293333
)
[6] => Array
(
[foo] => this thing2
)
)
)
要回显一个值:
echo $array["Thing1"][2]["anotherthing"]; // Result 19
希望这会有所帮助。