我会在你阅读文件时处理这个。
// how many total columns
$total = count( $row );
// get the halfway point (and round up if a decimal)
$middle = ceil( $total/2 );
// Form a new row using the first (0), last ($total-1) and middle ($middle)
$new_row = array( $row[0], $row[ $middle ], $row[ $total-1 ] );
嵌入到您的代码中:
function csv_to_array($filename='', $delimiter=',') {
if(!file_exists($filename) || !is_readable($filename)){
return FALSE;
}
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE) {
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
$total = count( $row );
$middle = ceil( $total/2 );
$new_row = array( $row[0], $row[ $middle ], $row[ $total-1 ] );
if(!$header) {
$header = $new_row;
}else{
$data[] = array_combine($header, $new_row);
}
}
fclose($handle);
}
return $data;
}
通过假设整个文件中的每一行将具有相同的列数,您可以减轻一些处理能力。如果是这样,您只需要计数一次,如下所示:
function csv_to_array($filename='', $delimiter=',') {
if(!file_exists($filename) || !is_readable($filename)){
return FALSE;
}
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE) {
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
if ( !$total ){ // Verify if we have the total yet, and if not:
$total = count( $row );
$middle = ceil( $total/2 );
}
$new_row = array( $row[0], $row[ $middle ], $row[ $total-1 ] );
if(!$header) {
$header = $new_row;
}else{
$data[] = array_combine($header, $new_row);
}
}
fclose($handle);
}
return $data;
}