Home > Software design >  How to split array to multiple csv files using PHP
How to split array to multiple csv files using PHP

Time:03-25

Help!

I want to make this part of code shorter and more transformative. My $named array looks like:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => Header
   
                )

            [1] => Array
                (
                    [0] => some text
                    [1] => some text

                )
        )

    [1] => Array
        (
            [0] => Array
                (
                    [0] => Header
                )

            [1] => Array
                (
                    [0] => 
                    [1] => some text
                )

            [2] => Array
                (
                    [0] => some text
                )
        )
 )

So, I would like to save to a new csv file if the number of "header" exceeds 100. How can I open and close a file with the correct index without having to manually type "/named_1" or "/named_2"? At the moment I have a y variable that goes through the $named array and writes to the file until there are 100 headers. How can I not repeat the code?

Also each line must have a total of 38 semicolons.


$file = fopen(__DIR__ . '/named_1.csv', 'w');
$file_2 = fopen(__DIR__ . '/named_2.csv', 'w');
$file_3 = fopen(__DIR__ . '/named_3.csv', 'w');
$y=0;
foreach ($named as $array) {
    foreach($array as $row){
        if($y < 100){
            $line = '';
            for ($i=0; $i <= 38; $i  ) { 
                if (count($row) > $i) {
                    $line .= $row[$i];
                    ($i != 38 ? $line .= ';' : '');
                } else {
                    ($i != 38 ? $line .= ';' : '');
                }
            }
            fwrite($file, $line.PHP_EOL); 
        }
        if($y > 99 && $y <200){
            $line = '';
            for ($i=0; $i <= 38; $i  ) { 
                if (count($row) > $i) {
                    $line .= $row[$i];
                    ($i != 38 ? $line .= ';' : '');
                } else {
                    ($i != 38 ? $line .= ';' : '');
                }
            }
            fwrite($file_2, $line.PHP_EOL); 
        }
        if($y > 199 && $y <300){
            $line = '';
            for ($i=0; $i <= 38; $i  ) { 
                if (count($row) > $i) {
                    $line .= $row[$i];
                    ($i != 38 ? $line .= ';' : '');
                } else {
                    ($i != 38 ? $line .= ';' : '');
                }
            }
            fwrite($file_3, $line.PHP_EOL); 
        }
    }
    $y  ;
}
fclose($file);
touch( __DIR__ . '/named_1.csv');
fclose($file_2);
touch( __DIR__ . '/named_2.csv');
fclose($file_3);
touch( __DIR__ . '/named_3.csv');

CodePudding user response:

Please try the following code. I added a function for composing filename for different needs.

function composeFilename($k, $mod, $type=1)
{
    switch($type)
    {
        // for named_1-100.csv, named_101-200.csv, ...
        case 1:
            $from = $k - $mod   2;
            $to = $k 1;
            $suffix = $from . "_" .$to;
            break;
        // for named_0-99.csv, named_100-199.csv, ...
        case 2:
            $from = $k - $mod   1;
            $to = $k;
            $suffix = $from . "_" .$to;
            break;
        // for named_1.csv, named_2.csv, ...
        default:
            $suffix = ($k % $mod) 1;
    }
    return "named_$suffix.csv";
}

$lines = [];
$mod = 100;// The max number of rows in each output file
$outputDirectory = __DIR__ . "/";
$lastIndex = count($named) - 1;
foreach ($named as $k => $array){
    foreach($array as $row){
        $lines[] = trim(implode(";", $row));
    }

    // Write output file for every $mod lines or for the rest
    if(($k 1) % $mod == 0 || $k == $lastIndex){
        $filename = $outputDirectory . composeFilename($k, $mod);
        if(file_put_contents($filename, implode(PHP_EOL, $lines))){
            // Reset lines array for the next chunk
            $lines = [];
        }
        else {
            die("$filename could not be saved.");
        }
    }
}
  • Related