2017-04-04 49 views
-1

我在txt文件上有這種結構。如何將txt文件轉換爲數組

[FILE_INFO] 
[FIRST] 
LOAD1= CPU 
LOAD2 = RAM  
[END_FIRST] 
[GLOBAL_INDEX] 
ELEC1=1235.12 
GAZ2,1=1563.123 
GAZ2,2= 28.56 
[END_GLOBAL_INDEX] 
[END_FILE_INFO] 

我需要的是將此txt結構轉換爲php數組,這是可能的或txt結構知道嗎?

Array 
(
    [FILE_INFO] => Array 
     (
      [FIRST] => Array 
       (
        [LOAD1] => CPU 
        [LOAD2] => RAM 
       ) 

      [GLOBAL_INDEX] => Array 
       (
        [ELEC1] => 1235.12 
        [GAZ2] => Array 
         (
          [1] => 1563.123 
          [2] => 28.56 
         ) 

       ) 

     ) 

) 

這裏是我的方法:

$txt_file = file_get_contents("test.rt"); 
$rows = explode("\n", $txt_file); 
$new_array = array(); $dimension = array(); 
    foreach($rows as $row =>$data) 
    {  
     if($data[0] == "[" && substr($data, 0, 4) != "[END"){ // start 
      $output = str_replace(array('[',']') , '' , $data); 
      array_push($dimension, trim($output)); 
      continue;  
     }else if(substr($data, 0, 4) == "[END"){ // end 
      $output = str_replace(array('[',']') , '' , $data); 
      array_pop($dimension); 
      continue;   
     } 
     $dim=""; 
     foreach($dimension as $k=>$v){ 
      $dim.= "['$v']"; 
     } 
     $new_array.$dim[] = $data; // this is not working !!!!! 
    } 

的問題是定位我的光標在陣列的尺寸,插入數據

+1

是,確定這是可能的。你應該嘗試一下吧! – Nytrix

+0

如果我問的是我已經嘗試過,但我看不到如何去做... – user3079885

+0

如果您嘗試過,請分享您的代碼並解釋您找到的問題。 –

回答

0

試試這個:

<?php 
$myfile = fopen("test.txt", "r"); 
// Iterate one line until end-of-file 
while(!feof($myfile)) { 
    $text[] = fgets($myfile); // Add the data in an array 
} 
fclose($myfile); 
print_r($text); // print the array 
?> 
相關問題