PHP CSV到关联数组,其中顶行作为键,列作为值数组

时间:2018-08-13 18:34:15

标签: php arrays csv

我正在尝试使用CSV文件创建多维数组,例如:

“ a”,“ b”,“ c”
1,2,3
4,5,6

将返回为:

array(  
    'a' => array(1, 4),  
    'b' => array(2, 5),  
    'c' => array(3, 6),  
    )

但是我有以下代码:

<?php
function readCSV($csvFile) {
    $aryData = [];
    $header = NULL;
    $handle = fopen($csvFile, "r");
    if($handle){
        while (!feof($handle)){
            $aryCsvData = fgetcsv($handle);
            if(!is_array($aryCsvData)){
                continue;
            }
            if(is_null($header)){
                $header = $aryCsvData;
            } 
            elseif(is_array($header) && count($header) == count($aryCsvData)){
                $aryData[] = array_combine($header, $aryCsvData);
            }
        }
        fclose($handle);
    }
    return $aryData;
}

print_r(readCSV("Book1.csv"));
?>

将其返回为:

Array(  
[0] => Array ( [a] => 1 [b] => 2 [c] => 3 )   
[1] => Array ( [a] => 4 [b] => 5 [c] => 6 )   
)

不胜感激!

2 个答案:

答案 0 :(得分:0)

在您进行操作时,无需构建末端阵列。此代码在循环之前读取标题行,然后仅将所有数据线读取到另一个数组中。然后,它将标头数组的每个元素与数据数组中的匹配列组合在一起(使用array_column()和标头元素的位置)...

function readCSV($csvFile) {
    $aryData = [];
    $output = [];
    $header = NULL;
    $handle = fopen($csvFile, "r");
    if($handle){
        $header = fgetcsv($handle);
        while ($aryData[] = fgetcsv($handle));
        foreach ( $header as $key=>$label) {
            $output[$label] = array_column($aryData, $key);
        }
        fclose($handle);
    }
    return $output;
}

答案 1 :(得分:0)

读取文件的第一行,并创建带有空列的关联数组。然后读取其余各行并遍历整个行,将值推入列数组。

<?php
function readCSV($csvFile) {
    $aryData = [];
    $handle = fopen($csvFile, "r");
    if($handle){
        $headerRow = fgetcsv($handle);
        if (!$headerRow) {
            return $aryData;
        }
        foreach ($headerRow as $colname) {
            $aryData[$colname] = [];
        }
        while ($aryCsvData = fgetcsv($handle)){
            foreach ($headerRow as $colname) {
                $aryData[$colname][] = each($aryCsvData);
            }
        }
        fclose($handle);
    }
    return $aryData;
}