2017-10-13 90 views
1

我有一個CSV文件看起來像這樣:轉換CSV到數組

Did,status 
"123","Active" 
"456","Not-Active" 
"789","Active" 
....and so on 

我希望能夠將其轉換成一個數組,看起來像這樣:

$DidStatus = array("123"=>"Active", "456"=>"Not-Active", "789"=>"Active"); 

我試過,但它不是我要找:

$file = file_get_contents("test.csv"); 
$data = array_map("str_getcsv", preg_split('/\r*\n+|\r+/', $file)); 
print_r($data); 

但輸出不TH Ë一個我在尋找:

Array 
(
    [0] => Array 
     (
      [0] => Did 
      [1] => status 
     ) 

    [1] => Array 
     (
      [0] => 123 
      [1] => Active 
     ) 

    [2] => Array 
     (
      [0] => 456 
      [1] => Not-Active 
     ) 

    [3] => Array 
     (
      [0] => 789 
      [1] => Active 
     ) 

    [4] => Array 
     (
      [0] => 
     ) 

) 
+1

你嘗試過這麼遠嗎?你卡在哪裏? –

+2

[如何使用PHP和fgetcsv函數從CSV文件創建數組](https://stackoverflow.com/questions/1269562/how-to-create-an-array-from-a-csv- file-using-php-and-the-fgetcsv-function) –

+1

你看過http://php.net/manual/en/function.fgetcsv.php – IncredibleHat

回答

2

看到fgetcsv()

<?php 

    $handle = fopen("test.csv", "r"); 
    $result = Array(); 
    fgetcsv($handle); //Removes the first line of headings in the csv 
    while($data = fgetcsv($handle)) { 
     $result[$data[0]] = $data[1]; 
    } 
    print_r($result); //the result 
?> 
+0

完美!謝謝 :) – compcobalt

-1

您可以使用此包league/csv,你可以找到關於如何使用它here指令 - 第一例子之一展示瞭如何CSV轉換爲數組

0

查找到fgetcsv。這意味着用於這樣的事情。

$arr = array(); 
$file = fopen('test.csv', 'r'); 
while (($result = fgetcsv($file)) !== FALSE) 
{ 
    $arr[] = $result; 
} 
fclose($file); 
2

還有其他的方法來做到這一點,但鑑於當前的代碼,只需通過0值提取1值並建立索引的數組。

unset($data[0]); //If needed to remove the header row 

$data = array_column($data, 1, 0); 

你可能認爲這是一個備用的第一步(不知道FILE_IGNORE_NEW_LINES是絕對必要):

$data = array_map('str_getcsv', file('test.csv', FILE_IGNORE_NEW_LINES));