将CSV转换为数组

时间:2017-10-13 14:55:24

标签: php

我有一个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);

但输出不是我要找的那个:

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] => 
        )

)

4 个答案:

答案 0 :(得分: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
?>

答案 1 :(得分:2)

还有其他方法可以做到,但是根据您当前的代码,只需提取1值的数组并按0值对其进行索引。

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));

答案 2 :(得分:0)

查看fgetcsv。这意味着用于这样的事情。

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

答案 3 :(得分:-1)

您可以使用此程序包league/csv,然后您可以找到有关如何使用它的说明here - 首批示例之一显示如何将csv转换为数组

相关问题