简体   繁体   English

如何在特定数组中存储列csv文件

[英]how to store column csv file in specific array

I have a CSV file with 8 column and i want to store any column into an array and working with them. 我有一个8列的CSV文件,我想将任何列存储到数组中并与它们一起工作。

Example:Num,UnitId,SubscriberId,ActivationType,StartTime,EndTime,LicenseCount,ProductId 例如:次数,单元ID,SubscriberId,ActivationType,开始时间,结束时间,LicenseCount,产品编号

how can i do this?? 我怎样才能做到这一点??

php code: php代码:

class CSVparse
  {
  var $mappings = array();
  function parse_file($filename)
    {
    $id = fopen($filename, "r");
    $data = fgetcsv($id, filesize($filename));
    if(!$this->mappings)
       $this->mappings = $data;
    while($data = fgetcsv($id, filesize($filename)))
        {
         if($data[0])
           {
            foreach($data as $key => $value)
               $converted_data[$this->mappings[$key]] = addslashes($value);
            $table[] = $converted_data;
             }
         }
    fclose($id);
    print_r($table);
    }
  }
$csv = new CSVparse;
$csv->parse_file("sample.csv");

output: 输出:

Array ( [0] => Array ( [Num] => 1 [UnitID] => 1 [SubscriberId] => 111 [ActivationType] => Standard [StartTime] => 8/5/2015 11:16 [EndTime] => 2015-09-05T11:16:00.7514332+04:30 [LicenseCount] => 2 [ProductId] => KISA1 ) [1] => Array ( [Num] => 2 [UnitID] => 1 [SubscriberId] => 222 [ActivationType] => Standard [StartTime] => 8/5/2015 11:16 [EndTime] => 2015-09-05T11:16:00.7514332+04:30 [LicenseCount] => 34 [ProductId] => KISA3 ) [2] => Array ( [Num] => 3 [UnitID] => 1 [SubscriberId] => 333 [ActivationType] => Standard [StartTime] => 8/5/2015 11:17 [EndTime] => 2015-09-05T11:17:27.6310205+04:30 [LicenseCount] => 12 [ProductId] => KISA6 ) [3] => Array ( [Num] => 4 [UnitID] => 1 [SubscriberId] => 444 [ActivationType] => Standard [StartTime] => 8/5/2015 11:17 [EndTime] => 2015-09-05T11:17:27.6310205+04:30 [LicenseCount] => 33 [ProductId] => KISA12 ) ) 

You can pass a field name to the function and do a check on that field it is set. 您可以将字段名称传递给函数,并检查设置的该字段。

class CSVparse
  {
  var $mappings = array();
  function parse_file($filename, $fieldname = false)
    {
    $id = fopen($filename, "r");
    $hdata = fgetcsv($id, filesize($filename));
    if(!$this->mappings)
       $this->mappings = $hdata;
    while($data = fgetcsv($id, filesize($filename)))
    {
        foreach($data as $key => $value) {
            if ($fieldname) if ($this->mappings[$key] != $fieldname) continue;
            $converted_data[$this->mappings[$key]] = addslashes($value);
        }
        $table[] = $converted_data;
    }
    fclose($id);
    print_r($table);
    }
  }
$csv = new CSVparse;
$csv->parse_file("sample.csv", 'UnitID');

To make it more usable you could make it an array of fields and do an array_search() in the conditional. 为了使它更有用,您可以使其成为字段数组,并在条件中执行array_search()

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

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