更新时间:2023-10-04 19:57:34
我会为你在文件中读取过程这一点。
I would process this as you're reading in the file.
// 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 ] );
您code中嵌入:
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;
}
您可以减轻一些处理能力,通过在整个文件假定每行将具有相同的列数。如果是这样,你只需要计算一次,就像这样:
You could alleviate some processing power, by assuming each row in the entire file will have the same column count. If so, you need only count once, like so:
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;
}