简体   繁体   中英

php create csv from associative array

I have to generate the csv from below array

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

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

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

)

and csv format should be as below,

sku1,bin1,10

sku1,bin2,10

sku2,bin2,10

sku2,bin10,9

sku3,bin3,7

How to archive this?

Try :

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

Try this example using fputcsv() function also read this link 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);

try : // set header to auto download file in 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM