我有一个包含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 ) )
答案 0 :(得分:1)
您可以将字段名称传递给该函数,并检查它所设置的字段。
[[NSOperationQueue mainQueue] addOperationWithBlock:^ {
[self.countDown invalidate];
}];
为了使它更有用,你可以把它变成一个字段数组,并在条件中做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');
。