<?php
namespace app\common\library;

class ExcelCsv{
    private $row;
    private $data;

    public function __construct($row,$data){
        $this->row[] = $row;
        $this->data = $data;
    }

    public function collection()
    {
        $row = $this->row;
        $data = $this->data;
        //设置表头
        foreach ($row[0] as $key => $value) {
            $key_arr[] = $key;
        }

        //输入数据
        foreach ($data as $key => &$value) {
            $js = [];
            for ($i=0; $i < count($key_arr); $i++) {
                $js = array_merge($js,[ $key_arr[$i] => $value[ $key_arr[$i] ] ]);
            }
            array_push($row, $js);
            unset($val);
        }

        $collect =  collect($row);

        $row = [];
        $list = [];
        foreach ($collect as $key=>$item){
            $val = [];
            foreach ($item as $v){
                $val[] = $v;
            }
            if ($key == 0){
                $row[] = $val;
            }else{
                $list[] = $val;
            }
        }

        return $list;
    }

    public function download($fileName,$row,$list)
    {
        $fileName = $fileName.'.csv';
        //设置文件头
        header('Content-Description: File Transfer');
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment; filename="' . $fileName . '"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');

        $fp = fopen('php://output', 'a');//打开output流
        mb_convert_variables('GBK', 'UTF-8', $row);
        fputcsv($fp, $row);

        foreach ($list as $val) {
            $val1 = [];
            foreach ($val as $export_obj) {
                $val1[] = iconv('utf-8', 'GB18030', $export_obj);
            }
            fputcsv($fp, $val1);
            //刷新缓冲
            ob_flush();
            flush();
        }
        fclose($fp);
        exit();
    }
}