2014-01-08 49 views
0

我有一個包含以下行把CSV內容爲穆蒂維數組

enter code here 

23,cars,43 063 
23,cars,17 306 
23,houses,13 300 
23,garage,13 094 
23,hotels,10 025 
22,cars,75 675 
22,cars,40 403 
22,houses,32 243 
22,garage,30 649 
22,hotels,29 734 
21,hotels,29 734 
22,hotels,29 734 

這裏是我使用的解析CSV文件中的代碼爲csv文件

 function readCSV($csvFile){ 
$file_handle = fopen($csvFile, 'r'); 
while (!feof($file_handle)) { 
    $line_of_text[] = fgetcsv($file_handle, 1024); 
} 



fclose($file_handle); 
return $line_of_text; 




    } 

當我顯示$ line_of_text的內容;陣,這裏是我得到

 Array 
     (
     [0] => Array 
     (
     [0] => 23 
     [1] => cars 
     [2] => 43 063 
    ) 

[1] => Array 
    (
     [0] => 23 
     [1] => cars 
     [2] => 17 306 
    ) 

[2] => Array 
    (
     [0] => 23 
     [1] => houses 
     [2] => 13 300 
    ) 

.....

但是,這不是我想要的,我想顯示在這種方式我陣列

array (
23 => array(
    'cars' => 43063, 
    'houses' => 17306, 
    'shops' => 13300, 
    'garages' => 13094, 
    'hotels' => 10025 
), 
22 => array(
    'cars' => 75675, 
    'houses' => 40403, 
    'shops' => 32243, 
    'garages' => 30649, 
    'hotels' => 29734, 
    'test' => 29734 
    ) 
    ); 

如何我是否實現了這個目標?你能幫我麼 ?

//最新通報新我數組的內容

Array 
(
[0] => Array 
    (
     [0] => cars 
     [1] => 00 
     [2] => 0 
    ) 

[1] => Array 
    (
     [0] => cars 
     [1] => 01 
     [2] => 0 
    ) 

[2] => Array 
    (
     [0] => cars 
     [1] => 02 
     [2] => 0 
    ) 


[3] => Array 
    (
     [0] => cars 
     [1] => 11 
     [2] => 0 
    ) 

[4] => Array 
    (
     [0] => cars 
     [1] => 23 
     [2] => 4425 
    ) 

[5] => Array 
    (
     [0] => houses 
     [1] => 00 
     [2] => 198 
    ) 

[6] => Array 
    (
     [0] => houses 
     [1] => 01 
     [2] => 742 
    ) 

[7] => Array 
    (
     [0] => houses 
     [1] => 02 
     [2] => 168 
    ) 
) 
+0

你可以很容易地重建數據,你想它通過循環,建設一個新的數組的方式,或通過建立數組,你可以通過原有的環路fgetcsv的(價值$ file_handle,1024去); – skrilled

+0

@skrilled,你有這樣的例子嗎?,我很新的php – user3172841

回答

1
$fp = fopen($csvFile, 'r'); 
$master = array(); 
while($line = fgetcsv($fp)) { 
    // 23,cars,43 063 
    if(!isset($master[$line[0]])) 
     $master[$line[0]] = array(); 

    if(!isset($master[$line[0]][$line[1]])) 
     $master[$line[0]][$line[1]] = 0; 

    $n = filter_var($line[2], FILTER_SANITIZE_NUMBER_INT); 
    $master[$line[0]][$line[1]] += $n; 
} 

var_dump($master); 

沒有測試,但應該工作。如果您有任何問題,請告訴我。

+0

白色的代碼,你是不是增加值... –

+0

哦,沒有注意到,鑰匙不是唯一的。輕鬆調整。 – Saeven

+0

是啊!現在應該工作! :P –

1

嘗試類似這樣!

$line_of_text=array(); 
while (!feof($file_handle)) { 
    $line = fgetcsv($file_handle, 1024); 

    if(isset($line_of_text[ $line[0] ][ $line[1] ])) 
     $line_of_text[$line[0]][$line[1]]+=str_replace(" ", "", $line[2]); 
    else 
     $line_of_text[$line[0]][$line[1]]=str_replace(" ", "", $line[2]); 

} 
+0

我曾嘗試使用@Saeven代碼將數據插入到新的csv文件中,但我正在爲數組中的每個鍵獲取新行。這是當我在csv文件中插入數據時得到的結果23,17306 23,13300 22,13094 22,10025我想爲每個鍵設置一行,並用「,」分隔值23,17306,13300 22,13094,10025可以嗎? – user3172841