-1

不要认为这很困难,但是经过一天的辛苦工作后,我无法解决这个小问题。我有一个简单的 csv 文件,我必须通过 php 显示,将列的值中的行分组。我们专门去:

这是我的 CSV 文件:

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

这就是我要打印的内容:

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 ---

我的出发点是这样的:

<?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);
?>
4

2 回答 2

1
<?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";
    }
}

输出:

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 ---
于 2015-03-13T23:11:15.353 回答
0

这是您想要执行的 php 代码的修改版本:

<?php
$Export= fopen("Test.csv", "r");
$found=array();
$lastart="";
while(!feof ($Export)){
    $riga=fgets($Export, 4096);
    $riga = str_replace(PHP_EOL, '', $riga);
    if($riga!=""){
            $val = explode(",", $riga);
            $code       =   $val[0];
            $art_n      =   $val[1];
            if ( $lastart != $art_n && $lastart != "") {
                    foreach ( $found as $col ) {
                            @$colorfound.=$col.",";
                    }
                    $colorfound = rtrim($colorfound, ",");
                    echo "--- Found $colorfound ---\n";
                    unset ($found);
                    $colorfound = "";
            }
            $color      =   $val[2];
            $found[]    =   $color;
            echo "$code-$art_n-$color\n";
            $lastart  =   $art_n;
    }
}
//The last art_n
foreach ( $found as $col ) {
        @$colorfound.=$col.",";
}
$colorfound = rtrim($colorfound, ",");
echo "--- Found $colorfound ---\n";
fclose($Export);
?>
于 2015-03-13T22:47:15.593 回答