Read .txt, set delimiter, remove duplicates

0

Good afternoon. I need my script to read a .txt like the example below:

4984538078766798|11|2016|246 
// Na primeira linha $a teria o valor de "4984538078766798"
// $b teria o valor de 11
// $c teria o valor de 2016
// $d teria o valor de 246
4108637744329741|07|2017|241
// Na segunda linha $a teria o valor de "4108637744329741"
// $b teria o valor de 07
// $c teria o valor de 2017
// $d teria o valor de 241
4984012022438078|08|2016|757 
// Na terceira linha $a teria o valor de "4984012022438078"
// $b teria o valor de 08
// $c teria o valor de 2016
// $d teria o valor de 757 

Ignore empty lines and remove duplicates.

I tried this way and did not succeed:

    $list = dirname(__FILE__) . "/lista.txt";

$content = file_get_contents($list);
$txt = preg_split("/[\r\n]/", $content, -1, PREG_SPLIT_NO_EMPTY);
$separa = trim('|', $txt);
$a = trim($separa[0]);
$b = trim($separa[1]);
$c = trim($separa[2]);
$d = trim($separa[3]);
    
asked by anonymous 05.06.2018 / 20:14

1 answer

0

One way to avoid duplicating elements is to use the element as the index of an array. So, every time you play the same index on it, it will be disregarded. So from what I understand of your question you want two things:

  • Disregard duplicate lines
  • Have a 'field' for each found value, properly 'exploded' with the delimiter '|'
  • The example below does this (you can also test at link ):

    <?php
    $linhas = array('123|45|1234|101', '999|88|777|666', '123|45|1234|101');
    foreach ($linhas as $linha)
        $arr[$linha] = NULL; // aqui se removem as linhas duplicadas
    echo "*** LINHAS ***\n";
    foreach ($arr as $key => $valor) { 
        echo $key . "\n"; // aqui se comprova o resultado final sem duplicatas
        $partes = explode ('|', $key);
        foreach ($partes as $parte) {
            $var[$parte] = NULL; // aqui se cria um array que resume todos os números sem duplicatas
        }
    }
    echo "*** CAMPOS ***\n";        
    foreach ($var as $key => $valor)
        echo $key . "\n"; // aqui se comprova o resultado de todos os campos finais sem duplicatas
    

    Since I do not have your file, I've simulated 3 lines within an array:

    $linhas = array('123|45|1234|101', '999|88|777|666', '123|45|1234|101');
    

    In your case, just ignore the code up to line 4, but insert the line read in $arr[$linha] = NULL .

    Running, results in:

    *** LINHAS ***
    123|45|1234|101
    999|88|777|666
    *** CAMPOS ***
    123
    45
    1234
    101
    999
    88
    777
    666
    

    As you can see, all of the two arrays I have used are NULL because they have no need to store anything in them, they were only used to remove any duplicates.

    link

        
    05.06.2018 / 21:20