2017-10-13 89 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));