php 仅从 csv 文件中选择第一列、中间列和最后一列

标签 php arrays fgetcsv

我有一个已上传的 csv 文件,我需要确定 csv 文件中有多少条目,并将第一列、中间列和最后一列格式化为具有 $header=>$value 对的关联数组。我有将整个 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;
}

但是,就确定执行此操作的方法而言,我仍然感到困惑。任何帮助,将不胜感激。我想可能的一件事是使用上面的这个函数来获取数组,然后编写一些其他函数来只获取这个数组的开始中间和结尾并转储其余部分(但仍然需要知道如何做到这一点)至于确定开头中间结尾

最佳答案

我会在您阅读文件时处理它。

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

关于php 仅从 csv 文件中选择第一列、中间列和最后一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16322185/

相关文章:

javascript - 将 php 2d 数组传递给 Javascript 并尝试使用 json_encode() 进行解析时会抛出未捕获的类型错误

php - 使用 file_get_contents() 时出现问题

android - 如何使用 Intent 共享数组中的所有项目?

PHP动态创建CSV : Skip the first line of a CSV file

php - 在 jQuery onClick 上,递增 PHP 变量?

javascript - PHP - 是否可以在一个文件中获取动态生成的值,以便在 if 语句中在另一个文件中使用?

ios - 按第二个单词对 nsarray 进行排序。 (按 "firstname surname"类字符串数组中的姓氏)

Javascript:通过数组映射后编辑变量

php - 将 CSV 转换为数组

php - 从 CSV 文件中删除行