简体   繁体   中英

Display same word in text file using PHP

I have text file as below:

text.txt

lebuzzdesbonsplans.com;hotmail.com;26608;828;3.11
lebuzzdesbonsplans.com;hotmail.fr;24798;876;3.53
friendcorp.fr;yahoo.fr;11343;0;0
friendcorp.fr;free.fr;9856;12;.12
friendcorp.fr;wanadoo.fr;9283;1;.01
messengear.fr;free.fr;9090;11;.12
messengear.fr;laposte.net;8107;2;.02
....................................
....................................

PHP code:

<?php
            $PMTA_FILE = file_get_contents("text.txt");
            $lineFromText = explode("\n", $PMTA_FILE);
            $title = "";
            $domain = "";
            foreach($lineFromText as $line){                    
                    $data = explode(";",$line);
                    $domain = $data[0];
                    if (array_key_exists($domain, $domains_seen)){
                        continue;

                    }
                 $domains_seen[$domain] = true; 
                 echo $domain;
                 echo "<br>";
                 echo $data[2]; 
                 echo "<br>";   
          }


?>

But the result of this code:

lebuzzdesbonsplans.com 
26608
friendcorp.fr
11343
messengear.fr
9090

I do not want the result as above, I need the result as below:

lebuzzdesbonsplans.com 
26608
24798
friendcorp.fr
11343
9856
9283
messengear.fr
9090
8107

Anyone know help me to get the solution please,Thanks.

You can use

$lines = array_reduce(file("text.txt", FILE_IGNORE_NEW_LINES), function ($a, $b) {
    $b = str_getcsv($b, ";");
    $a[$b[0]][] = $b[2];
    return $a;
});


foreach($lines as $k => $values)
{
    echo $k,PHP_EOL;
    echo implode(PHP_EOL, $values);
    echo PHP_EOL;
}

Output

lebuzzdesbonsplans.com
26608
24798
friendcorp.fr
11343
9856
9283
messengear.fr
9090
8107
natsort($lineFromText);
foreach($lineFromText as $line){                    
    $data = explode(";",$line);
    $domain = $data[0];
    if (!array_key_exists($domain, $domains_seen)){
        echo $domain;
        echo "<br>";
    }
    echo $data[2]; 
    echo "<br>";   
    $domains_seen[$domain] = true; 
}

Update: sort the lines first - that way all the domains will be collected together,

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