php从关联数组创建csv

时间:2018-04-24 08:02:32

标签: php arrays export-to-csv

我必须从数组下面生成csv

Array
(
    [sku1] => Array
        (
            [bin1] => 10
            [bin2] => 5
            [bin3] => 10
        )

    [sku2] => Array
        (
            [bin2] => 10
            [bin10] => 9
        )

    [sku3] => Array
        (
            [bin3] => 7
        )

)

和csv格式应如下所示,

SKU1,bin1,10

SKU1,bin2,10

SKU2,bin2,10

SKU2,bin10,9

SKU3,bin3,7

如何存档?

3 个答案:

答案 0 :(得分:1)

尝试:

                    $array= [
                        'sku1' => [
                            'bin1' => 10,
                            'bin2' => 5,
                            'bin3' => 10
                        ]
                        ,
                        'sku2' => [
                            'bin2' => 10,
                            'bin10' => 9,
                        ],
                        'sku3' => [
                            'bin3' => 7
                        ]
                    ];

                    $fileContent=[];

                    foreach ($array as  $key =>$value1){
                         foreach ($value1 as $key2 => $value2){
                             $fileContent[]=[$key, $key2, $value2];
                         }
                    }


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

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

                    fclose($fp);

答案 1 :(得分:0)

使用fputcsv()函数尝试此示例也请阅读此链接for getting an idea about fputcsv()

$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);

答案 2 :(得分:0)

尝试:     //在csv foramt中将标题设置为自动下载文件

header("Content-Disposition: attachment; filename=\"demo.xls\"");
header("Content-Type: application/vnd.ms-excel;");
header("Pragma: no-cache");
header("Expires: 0");
$out = fopen("php://output", 'w');
//this is your data array to be converted in csv 

$result= 
array('sku1'=>array('bin1'=>10,'bin2'=>5,'bin3'=>10),'
sku2'=>array('bin2'=>10,'bin10'=>3),'sku3'=>array('bin3'=>7));

$final=array();
// now se are converting first array key in to node
foreach($result as $key=>$val){
// now se are converting second array key and value in to node
foreach ($val as $k=>$v){
// merging first array key and second array key values in to single array to 
//make a csv
$final[]=array($key,$k,$v);
}

}

foreach ($final as $data)
{
  //Now we are generating the csv from final array 
  fputcsv($out, $data,"\t");
}   
fclose($out);