简体   繁体   中英

Save multiple arrays as columns into a csv file

I want to write mutliple arrays in one output csv, in which each array represents a column. If I use two loops, the output is below the output from the firt loop..

My code is:

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

foreach ($ordernumber as $line)  {
    fputcsv($fp,explode(',',$line));
}

foreach ($currency as $line)  {
    fputcsv($fp,explode(',',$line));
} 

fclose($fp);

and here the output:

item_sku
1126204
1126220
1126230
1126250
1126252
1126256
1126257
1126258
1126260
1126261
1126116.54
currency
EUR
EUR
EUR
EUR
EUR
EUR
EUR
EUR
EUR
EUR
EUR
EUR

So, but i need the output side by side - like an regular csv file.

Does anyone have a start for me?

Assuming the lines in both arrays match each other ie line 1 = line 1 you have to do it in one loop. One way would be to use the index of the array you are processing to access the other array.

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

// add col headings    
fputcsv($fp,[ 'item_sku','currency' ]);

foreach ($ordernumber as $idx => $line)  {
    fputcsv($fp,[ $line,$currency[$idx] ]);
}

But I would start by looking at how you managed to generate 2 arrays that contain related data but are not the same array and fix that

here is 1 way to do this, you have to create an array for every line, then put those into csv:

//first create a array like this.
//manually
$mycsv[1] = array('EUR', '1126261');
$mycsv[2] = array('EUR', '1128961');
$mycsv[3] = array('EUR', '1126791');

//programitically; assuming both array are equally based on line by line rows
$mycsv = array();
for ($i=0;$i<count($arr1);$i++){
     $mycsv[$i] = array($arr1[$i],$arr2[$i]);
}

$fp = fopen('output.csv','w');
foreach ($mycsv as $line) {
   fputcsv($fp, $line, ',');
}
fclose($fp);

To complete @RiggsFolly answer, you can do this if yours arrays doesn't have the same indexes :

// Check your two arrays have the same size
if (count($ordernumber) === count($currency)) {

    $fp = fopen('output.csv','w');
    foreach ($ordernumber as $line)  {
        fputcsv($fp, [$line, array_shift($currency)]);
    }
    fclose($fp);
}

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