将csv转换为关联数组

时间:2012-02-24 17:38:51

标签: php arrays csv

我有一个CSV文件,其中包含来自http://jotform.com/数据源的26个字段。该文件由逗号分隔,字段用双引号括起。数据包含逗号。这真的很震撼。此外,CSV全部在一行......

是否有人熟悉可以处理将CSV转换为关联数组的程序?

如果数组由标题而不是数字键索引,我更喜欢。 我已经尝试了几乎所有的http://us.php.net/fgetcsv函数并取得了成功。

我尝试过的代码:

<?php
    function get2DArrayFromCsv($file,$delimiter) {
        if (($handle = fopen($file, "r")) !== FALSE) {
            $i = 0;
            while (($lineArray = fgetcsv($handle, 4000, $delimiter)) !== FALSE) {
                for ($j=0; $j<count($lineArray); $j++) {
                    $data2DArray[$i][$j] = $lineArray[$j];
                }
                $i++;
            }
            fclose($handle);
        }
        return $data2DArray;
    }
?>

$file_path = "../../Reunion-Memory-Book-Form.csv";

if (($handle = fopen($file_path, "r")) !== FALSE) {
    # Set the parent multidimensional array key to 0.
    $nn = 0;
    while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
        # Count the total keys in the row.
        $c = count($data);
        # Populate the multidimensional array.
        for ($x=0;$x<$c;$x++)
        {
            $csvarray[$nn][$x] = $data[$x];
        }
        $nn++;
    }
    # Close the File.
    fclose($handle);
}
print'<pre>';print_r($csvarray);print'</pre>';exit;

1 个答案:

答案 0 :(得分:0)

由于CSV显然是一个巨大的混乱...我选择使用Excel转储,这是工作代码:

require_once('../../lib/PHPExcel.php');

$file_path = "../../Reunion-Memory-Book-Form.xls";

$inputFileName = $file_path;
$sheetname = 'Responses';

/**  Identify the type of $inputFileName  * */
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
/**  Create a new Reader of the type defined in $inputFileType  * */
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
/**  Advise the Reader that we only want to load cell data  * */
$objReader->setReadDataOnly(true);
/**  Advise the Reader of which WorkSheets we want to load  * */
$objReader->setLoadSheetsOnly($sheetname);
/**  Load $inputFileName to a PHPExcel Object  * */
$objPHPExcel;
try {
    /** Load $inputFileName to a PHPExcel Object  * */
    $objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
} catch (Exception $e) {
    die('Error loading file: ' . $e->getMessage());
}

$objWorksheet = $objPHPExcel->getActiveSheet();

$rowdata = $data = array();
$importCells = array(
    'Submission Date', // 0
    'Name', // 1
    'Major', // 2
    'Street Address', // 3
    'Street Address Line 2', // 4
    'City', // 5
    'State / Province', // 6
    'Postal / Zip Code', // 7
    'Country', // 8
    'Home Phone', // 9
    'Cell Phone', // 10
    'Office Phone', // 11
    'E-mail', // 12
    'Employer/Retired', // 13
    'Job Title', // 14
    'Are you planning to attend reunion?', // 15
    'Spouse/Partner Name', // 16
    'Spouse/Partner Employer', // 17
    'Spouse/Partner Job Title', // 18
    'Spouse/Partner University and Class Year', // 19
    'Children: (list names/ages)', // 20
    'CMC Memories', // 21
    'Interests/Hobbies', // 22
    'Student Activities/Clubs', // 23
    'Volunteer Work (include services)', // 24
    'Life Since', // 25
    'Images', // 26
);

$data = array();
foreach ($objWorksheet->getRowIterator() as $row)
{
    $cellIterator = $row->getCellIterator();
    $cellIterator->setIterateOnlyExistingCells(true);
    $rowdata = array();
    foreach ($cellIterator as $i => $cell)
    {
        if (isset($importCells[$i])) $rowdata[$importCells[$i]] = $cell->getValue();
    }
    $data[] = $rowdata;
}
print'<pre>Array: ';print_r($data);print'</pre>';exit;
exit;