2012-09-16 119 views
0

目前我有一個看起來是這樣的文件:爆炸.txt文件到多維數組

Awesomedude123 = 399,408 = September 16, 2012: 
Username11 = 1,914,144 = September 16, 2012: 
EpicSurfer = 1,031,427 = September 16, 2012: 

我想要做的就是它改造成用PHP多維數組,所以它看起來是這樣的:

Array 
(
    [1] => Array 
    (
     [0] => Awesomedude123 
     [1] => 399,408 
     [2] => September 16, 2012 
    ) 

[2] => Array 
    (
     [0] => Username11 
     [1] => 1,914,144 
     [2] => September 16, 2012 
    ) 

[3] => Array 
    (
     [0] => EpicSurfer 
     [1] => 1,031,427 
     [2] => September 16, 2012 
    ) 

) 

我試過使用array_shift,但它沒有解決。任何幫助將高度讚賞!

+1

發佈您的代碼,你試過嗎? –

回答

2

下面是代碼:

<?php 

$data = file_get_contents('File.txt'); // Get the file content 
$data = str_replace(array("\n", "\r"), '', $data); // Clear newline characters 

$data = explode(':', $data); // Get each record by : at end of line 

unset($data[count($data) - 1]); // Clear the last empty element 

$final_array = array(); 
foreach($data AS $row){ // Loop the exploded data 
    $final_array[] = explode(' = ', $row); // Explode each row by Space=Space to each row of final_array 
} 

print_r($final_array); 

?> 
+0

工作就像一個魅力!謝謝! – user1676019

2

您可以使用正則表達式來分割你的字符串:

myarray = array(); 
$file = fopen("myfile",'r'); 
while (!feof($file)) { 
    $line = fgets($file); 
    preg_match("/(\w+) = (.+) = (.+)/",$line,$matches); 
    myarray[] = array($matches[1],$matches[2],$matches[3]); 
}