2013-05-01 106 views
3

我有一个csv文件上传,我需要确定csv文件中有多少条目,并将第一列,中间列和最后一列格式化为关联数组$头=> $值对。我有代码格式化整个csv到阵列php从csv文件中只选择第一列,中间列和最后一列

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(!$header) { 
      $header = $row; 
     }else{ 
      $data[] = array_combine($header, $row); 
     } 
    } 

    fclose($handle); 
} 

    return $data; 
} 

然而,我坚持尽可能确定如何做到这一点。任何帮助,将不胜感激。有一件事可能是我想要的是使用上面的函数获取数组,然后编写一些其他函数来获取该数组的开始中间和结尾,然后转储剩余的数据(但仍然需要知道如何做到这一点。就决定开始中间和结尾

+0

之后加上以下'$ row = array($ row [0],$ row [floor(sizeof($ row)/ 2)], $行[的sizeof($行)-1]);' – Waygood 2013-05-01 16:30:05

回答

6

为你的文件中读取我会处理这个

// 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; 
} 

你可以减轻一些处理能力通过假定整个文件中的每一行都会有e相同的列数。如果是这样,你只需要计数一次,就像这样:

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; 
} 
相关问题