简体   繁体   English

从PHP中的csv列创建数组

[英]Creating arrays from csv columns in PHP

I've never worked with csv files before and I'm hoping to create arrays in php from the columns. 我以前从未使用过csv文件,我希望从列中用php创建数组。

So for example the csv would look something like this: 因此,例如,csv看起来像这样:

Name, Address, DOB 名称,地址,DOB

john doe, 22 grove street, 06,06,2006 约翰·多伊,格罗夫街22号,2006年6月6日

i'd like each of the columns to be an array named by the column headings. 我希望每个列都是由列标题命名的数组。 Any time I parse the file(test.csv) i get arrays of the table rows instead. 每当我解析文件(test.csv)时,我都会得到表行的数组。

Following code will do the work for you. 以下代码将为您完成工作。 And you can see the real working script of the exactcode at this url: 您可以在以下网址中看到确切代码的实际工作脚本:

http://sugunan.net/demo/csv1.php http://sugunan.net/demo/csv1.php

$i=0;
$filename = 'data1.csv';
$contents = file($filename);



foreach($contents as $line) {
    $line = preg_replace( "/\r|\n/", "", $line );
    $line_array = explode(",",$line);
    if($i==0)
    {
        foreach($line_array as $key=>$val)
        {
            $csv_heading[$key] = trim($val);
        }
    }
    else
    {
        foreach($line_array as $key=>$val)
        {
            $csv_array[$i][$csv_heading[$key]] = $val;
        }
    }
    $i++;
}

print_r($csv_array);

data file url: http://sugunan.net/demo/data1.csv 数据文件网址: http : //sugunan.net/demo/data1.csv

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM