二话不说 直接上代码
function getCSVdata($filename)
{
$row = 1;//第一行开始
if(($handle = fopen($filename, "r")) !== false){
while(($dataSrc = fgetcsv($handle)) !== false){
$num = count($dataSrc);
for ($c=0; $c < $num; $c++){//列 column
if($row === 1){//第一行作为字段
$dataName[] = $dataSrc[$c];//字段名称
}else{
foreach($dataName as $k=-->$v){
if($k == $c){//对应的字段
$data[$v] = $dataSrc[$c];
}
}
}
}
if(!empty($data)){
$dataRtn[] = $data;
unset($data);
}
$row++;
}
fclose($handle);
return $dataRtn;
}
}
$aData = getCSVdata('test.csv');
var_dump($aData);
CSV文件内容:
得到的结果是:
array
0 =>
array
'detail' => string 'a1' (length=2)
'nickname' => string 'b1' (length=2)
'title' => string 'c1' (length=2)
1 =>
array
'detail' => string 'a2' (length=2)
'nickname' => string 'b2' (length=2)
'title' => string 'c2' (length=2)
2 =>
array
'detail' => string 'a3' (length=2)
'nickname' => string 'b3' (length=2)
'title' => string 'c3' (length=2)