PHP:当特定值相等时对csv行进行分组[关闭]
问题描述:
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);
?>
答
<?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) . "
";
}
echo "--- Found " . implode(',', array_keys($line['colours'])) . " ---
";
}
}
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 ---
答
Here is a modified version of your php code doing what you want:
<?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 ---
";
unset ($found);
$colorfound = "";
}
$color = $val[2];
$found[] = $color;
echo "$code-$art_n-$color
";
$lastart = $art_n;
}
}
//The last art_n
foreach ( $found as $col ) {
@$colorfound.=$col.",";
}
$colorfound = rtrim($colorfound, ",");
echo "--- Found $colorfound ---
";
fclose($Export);
?>