在PHP中将多个动态数组数据导出为CSV文件

时间:2016-01-05 00:22:47

标签: php export-to-csv

我的目标是生成一个转换为偶数,奇数和斐波那契的数字列表。但是,我想将屏幕上生成的数字的结果导出到CSV文件。我想将所有动态结果存储在一个数组中以传递给导出函数。 My Export适用于静态数组数据,但我的挑战是如何将多个动态数组数据存储在一个数组中以传递给导出函数。

如何在$ content数组中存储函数调用的数组结果?

$content = array($evenNumbers,$oddNumbers,$fibonacci);

> <?php
> 
>     //request form actions using hidden form field
>     $job = (!isset($_REQUEST["job"])) ? '' : trim($_REQUEST["job"]);
> 
>     $export = (!isset($_REQUEST["export"])) ? '' : trim($_REQUEST["export"]);
> 
>     $evenNumbers = array();
> 
>     $oddNumbers = array();
>     $fibonacci = array();
>     $file = new FileDataClass();
> 
>     //performed when user click upload button
>     if ($job == "uploadFile") {
>         
>         //get file from file upload in form 
>         $file->FileData($_FILES["aNumbers"]);
> 
>         $evenNumbers = $file->GetEvenNumbers();
>         $fibonacci = $file->GetFibonacciNumbers();
>         $oddNumbers = $file->GetOddNumbers();
>     }
> 
> 
>     //performed when user click export button
>     
>     elseif($export == "exportFile"){
> 
> 
> 
> 
>         //get file from file upload in form 
>         $file->FileData($_FILES["aNumbers"]);
> 
>         $evenNumbers = $file->GetEvenNumbers();
>         $fibonacci = $file->GetFibonacciNumbers();
>         $oddNumbers = $file->GetOddNumbers();
> 
>     
> 
>         $content = array($evenNumbers,$oddNumbers,$fibonacci);
> 
>     
>    
>     // csv file name 
>     $filename  = "exportnumbers.csv";
> 
> 
>  
>  
> 
>     //pass file name and array of content to export
>     
>      
>           $file->ExportNumbers($content,$filename);
>     
>     }
>     ...
> 
> ?>

1 个答案:

答案 0 :(得分:-1)

参考fputcsv()手册http://php.net/manual/en/function.fputcsv.php。 这是上面链接的一个例子。

<?php

    $list = array (
        array('aaa', 'bbb', 'ccc', 'dddd'),
        array('123', '456', '789'),
        array('"aaa"', '"bbb"')
    );

    $fp = fopen('file.csv', 'w');

    foreach ($list as $fields) {
        fputcsv($fp, $fields);
    }

    fclose($fp);
    ?>