Search code examples
phparrayscsvforeachfeof

PHP: Grouping csv lines when a specific value is equal


Do not think it's difficult , but after a hard day's work I can not get on top of this trivial problem . I have a simple csv file that I have to show through php , grouping the lines from the value of a column . We go specifically :

This is my CSV file:

15000,art1,black
15000,art1,white
15000,art1,green
20000,art2,black
20000,art2,white
25000,art3,black

And this is what I want to print:

15000-art1-black
15000-art1-white
15000-art1-green
--- Found black,white,green ---
20000-art2-black
20000-art2-white
--- Found balck,white ---
25000-art3-black
--- Found black ---

My starting point is this:

<?php
$Export= fopen("Test.csv", "r");
while(!feof ($Export)){
    $riga=fgets($Export, 4096);
    if($riga!=""){
        $data=split(',',$riga);
        foreach ($data as $line) {
            $val = explode(",", $line); 
            $code       =   $val[0];
            $art_n      =   $val[1];
            $color      =   $val[2];
        }
    }
}
fclose($Export);
?>

Solution

  • <?php 
    
    if (($handle = fopen("Test.csv", "r"))) {
        $lines = array();
        while (($columns = fgetcsv($handle))) {
    
            $number = $columns[0];
            $colour = $columns[2];
    
            if (!isset($lines[$number])) {
                $lines[$number] = array('instances' => array(), 'colours' => array());
            }
    
            $lines[$number]['instances'][] = $columns;
            $lines[$number]['colours'][$colour] = 1;
        }
    
        fclose($handle);
    
        foreach ($lines as $number => $line) {
            foreach ($line['instances'] as $instance) {
                echo implode('-', $instance) . "\n";
            }
            echo "--- Found " . implode(',', array_keys($line['colours'])) . " ---\n";
        }
    }
    

    Output:

    15000-art1-black
    15000-art1-white
    15000-art1-green
    --- Found black,white,green ---
    20000-art2-black
    20000-art2-white
    --- Found black,white ---
    25000-art3-black
    --- Found black ---