Php 如何在特定数组中存储列csv文件
我有一个8列的CSV文件,我想将任何列存储到一个数组中并使用它们 示例:Num、UnitId、SubscriberId、ActivationType、StartTime、EndTime、LicenseCount、ProductId 我该怎么做 php代码:Php 如何在特定数组中存储列csv文件,php,csv,Php,Csv,我有一个8列的CSV文件,我想将任何列存储到一个数组中并使用它们 示例:Num、UnitId、SubscriberId、ActivationType、StartTime、EndTime、LicenseCount、ProductId 我该怎么做 php代码: class CSVparse { var $mappings = array(); function parse_file($filename) { $id = fopen($filename, "r");
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\u search()
。代码的输出将为所有列返回此值:array([0]=>array([Num]=>1)[1]=>array([Num]=>2)[2]=>array([Num]=>3][3]=>array([Num Num]=>4))编辑以修复错误-密钥需要映射到字段名