vaibhavsulake
vaibhavsulake

Reputation: 1

How to concatenate 3 row value which is present in same column csv file using php

i trying to uploda csv file to database using php. i want to concat 3 rows which is present in same columan how to do that

$handle = $_FILES['file']['tmp_name'];
$file = fopen($handle, 'r');
fgetcsv($file, 10000, ",");
$TO='FR'; 
$i=1; 
$sql = 'insert into excel(startdate,enddate) values ';
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE) {
    if($TO=='to'){
        $enddate = $emapData[0];
        $TO = "FR";
        $i=2;
    }elseif($TO=='FR'){
        $startdate = $emapData[0];
        $TO = $emapData[0];
        $i=1;
    }
     if($TO!='FR'){
         $TO = $emapData[0];
     }
     if($i==2){
          
         $sql .= "('$startdate','$enddate'),";
     }
     
}
$sql = substr_replace($sql, ";", -1);
$stmt = mysqli_prepare($conn,$sql);
mysqli_stmt_execute($stmt);
echo $sql;
fclose($file);

My csv format it contain date and monday value my first problem was i have to seprate sartdate and enddate from date which is done but now i want to concat the mon value first 3 row vice versa till end

enter image description here

Upvotes: 0

Views: 36

Answers (1)

tim
tim

Reputation: 2722

If you can't get the CSV format right from the beginning I wouldn't use the CSV parser for this. Try something like this using regular expressions to extract data:

<?php

  //$content = file_get_contents($_FILES['file']['tmp_name']);

  $content = 'FROM,TO' . PHP_EOL
           . '06-05-2019,2' . PHP_EOL
           . 'to,6' . PHP_EOL
           . '11-05-2019,7' . PHP_EOL
           . '13-05-2019,5' . PHP_EOL
           . 'to,7' . PHP_EOL
           . '18-05-2019,8';

  // Remove header
  $content = preg_replace('#^.*?\R+#', '', $content);

  // Split into sets
  foreach (preg_split('#(?<=\d{2}-\d{2}-\d{4},\d)\R+(?=\d{2}-\d{2}-\d{4})#', $content) as $set) {
      
   // Extract from set
    $extracts = preg_split('#[\r\n\t,;]+#', $set); // Split values by new line character, tab, comma, or semicolon
    var_dump($extracts);
  }

Or if you like one liners:

preg_match_all('#(\d{2}-\d{2}-\d{4})[\t,;](\d)\R+to[\t,;](\d)\R+(\d{2}-\d{2}-\d{4})[\t,;](\d)#', $content, $extracts);
var_dump($extracts);

Upvotes: 0

Related Questions