簡體   English   中英

如何在特定數組中存儲列csv文件

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

我有一個8列的CSV文件,我想將任何列存儲到數組中並與它們一起工作。

例如:次數,單元ID,SubscriberId,ActivationType,開始時間,結束時間,LicenseCount,產品編號

我怎樣才能做到這一點??

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

輸出:

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

您可以將字段名稱傳遞給函數,並檢查設置的該字段。

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

為了使它更有用,您可以使其成為字段數組,並在條件中執行array_search()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM