0

I was trying to find answer but i was not successful, please help.

I'm trying to populate multiple rows from data.txt by preg_match to single row or column in data.csv. It needs to be in single array because I need only unique numbers. -> or any other option the get only unique numbers

I was not able to merge arrays to single array and populate it like one array to single row. I will be truly happy for any advice.

Here is my simplified code:

$filename = 'data.txt';
$fupids = array ();

$handle = fopen($filename, "r");
if (!$handle) exit;

    while (($line = fgets($handle)) !== false) {
        if (preg_match_all('/([0-9]{8})/',$line,$output)) {
            $fupid = $output[0];
            $file = fopen('data.csv', 'a+');
            fputcsv($file, array_unique($output[0]));           
        }
    }
fclose($file);

Here is my simplified data.txt :

10153231,10159512,10159512,10159512
10141703,10160541,10160541
10165815,10158007,10158007

current csv output :

10153231,10159512
10141703,10160541
10165815,10158007

desirable output is only one row or maybe better one column like this:

10153231,10159512,10141703,10160541,10165815,10158007

Thanks all for help.

Simon
  • 17
  • 1
  • 4
  • Does the file `data.csv` already exists when your script starts? And in fine, what do you want? One row or one column? Also, what's the size of the input file? – Casimir et Hippolyte Nov 08 '17 at 19:00
  • It doesn't matter but yes data.csv exist and it is empty. Like I said it doesn't matter if it will be one row or 1 column i will take both solution. Size of input file is150mb logs of text data.I will be totally satisfied if I will get solution for this set of data to transform it to 1 row or column. – Simon Nov 08 '17 at 21:06

1 Answers1

0

Perhaps something like this (not tested): (idea: duplicate keys are overwritten with array_merge)

$filename = 'data.txt';
$fupids = [];

if ( false === $hin = fopen($filename, 'r') )
    throw new Exception('unable to open input file');

if ( false === $hout = fopen('data.csv', 'a+') )
    throw new Exception('unable to open output file');

while ( false !== $fields = fgetcsv($hin) ) {
    $fupids = array_merge($fupids, array_flip($fields));
}

fclose($hin);
fwrite($hout, implode(',', array_keys($fupids)));
fclose($hout);
Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
  • following errors appeared: Notice: Undefined variable: fupid in C:\...\selectfup id.php on line 18 Warning: array_keys() expects parameter 1 to be array, null given in C:\...\selectfupid.php on line 18 Warning: implode(): Invalid arguments passed in C:\...\selectfupid.php on line 18 – Simon Nov 09 '17 at 13:35
  • @Simon: it's only a typo, `$fupid` => `$fupids`. – Casimir et Hippolyte Nov 09 '17 at 14:00
  • I figure that out with $array = array_merge($array,$output[0]); – Simon Nov 09 '17 at 14:05