如何在CSV导出中动态设置标题?

时间:2019-04-10 21:15:07

标签: php arrays sorting export-to-csv

我们有一个基于PHP的网站,该网站根据精选的Markdown文件生成CSV导出。我们可以选择一个月的文件并以这种方式导出。

我们试图实现的目标是通过以下方式制作CSV标头:

  • 动态包含所有降价文件中的每个标头
  • 如果可能的话,每个月以相同的顺序包含标题

一些简单的Markdown文件示例

文件1:

b: 'value'
c: 'value'
d: 'value'

文件2:

a: 'value'
b: 'value'
d: 'value'

文件3:

a: 'value'
c: 'value'
d: 'value'

将这些导出为CSV文件,我希望标题为 一个| b | c | d

因为它将以某种方式即时找出

  • 文件1。c总是在b之后,d总是在c之后。
  • 文件2。a总是在b之前,d总是在b之后。
  • 文件3。a总是在c之前(现在已经是这种情况),c总是在d之前

也许我把那部分复杂化了。

如果我没有清楚说明这一点,我事先表示歉意。我研究了array_uniquearray_merge,但不确定是否有这两个方法可以帮助我实现自己的目标。

现有功能是这样:

    /**
     * Handle the request if requesting a group is exported to CSV
     */
    public function exportGroupToCsv($year=null,$month=null)
    {
        /** @var Uri $uri */
        $uri      = $this->grav['uri'];
        $segments = $uri->paths();

        $typePath = $this->getTypePath($segments[2]);

        if (!is_dir($typePath)) {
            throw new \RuntimeException('No data found', 404);
        }

        $headers = [];
        $rows    = [];

        /** @var \SplFileInfo $file */
        foreach (new \FilesystemIterator($typePath) as $file) {


            $thisyear = substr($file->getFilename(), 2,2);
            $thismonth = substr($file->getFilename(), 4,2);
            $thisdate = substr($file->getFilename(), 6,2);
            $thishour = substr($file->getFilename(), 9,2);
            $thisminute = substr($file->getFilename(), 11,2);
            $thissecond = substr($file->getFilename(), 13,2);

            if(!$year || ($thisyear == $year && $thismonth == $month)){
                $record = Yaml::parse(File::instance($file->getPathname())->content());

                if (empty($headers)) {
                    $headers = array_merge(['Date'], array_keys($record));
                }

                $sortedRow = [];

                foreach ($headers as $key) {
                    if($key == 'Date'){
                        $sortedRow[$key] = $thismonth."/".$thisdate."/".$thisyear." ".$thishour.":".$thisminute.":".$thissecond;
                    }else{
                        if(array_key_exists($key, $record)){
                            $sortedRow[$key] = $record[$key];
                        }else{
                            $sortedRow[$key] = '';
                        }
                    }
                }

                $rows[] = $sortedRow;
            }

        }

        // Output headers so that the file is downloaded rather than displayed
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename='.$segments[2].'.csv');

        // Create a file pointer connected to the output stream
        $output = fopen('php://output', 'w');

        // Output the column headings
        fputcsv($output, $headers);

        // Output the values
        foreach ($rows as $row) {
            fputcsv($output, array_values($row));
        }

        fclose($output);

        exit;
    }

谢谢

1 个答案:

答案 0 :(得分:0)

一旦将字母排列在数组中,就可以对数字和数字使用minmax函数。同样是比较和递增!

<?php
$letters = str_split("abdh");
$min = min($letters);
$max = max($letters);
for ($i = $min; $i <= $max; $i++) {
    echo $i;
}

输出:

abcdefgh

(确定这是纯粹的荒谬,还是出色的PHP功能留给读者练习。)