如何对逗号分隔值进行分组
问题描述:
I want group the comma separated values in the columns. For example, in the following data, I want to group the first value of each row in a group A, second in group B and so on. The values are random and the purpose is to generate an XML file.
Sample data:
1,2,3,4,5
3,5,4,6,2
Desired output:
<group n="A">
<col n="V"><col_value>1</col_value></col>
<col n="V"><col_value>3</col_value></col>
</group>
<group n="B">
<col n="V"><col_value>2</col_value></col>
<col n="V"><col_value>5</col_value></col>
</group>
What I'm trying:
I'm trying following code, I'm only unable to figure out how to create a group only once and then put the values in it,
$a_exists = 0;
$b_exists = 0;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($d = fgetcsv($handle)) !== FALSE) {
//create group A
if ($a_exists != 1){
$xml->startElement('group');
$xml->writeAttribute('n', 'A');
}
$xml->startElement('col');
$xml->writeAttribute('n', 'V');
$xml->writeElement('col_value', $d[0]);
$xml->endElement();
if ($a_exists != 1){
$xml->endElement();
$a_exists = 1;
}
//repeat above code to generate group B.
}
}
答
What I Would do is group them first, per column, then create the XML. Sample:
// open csv
$fh = fopen('test.csv', 'r');
$data = array();
while(!feof($fh)) {
$row = fgetcsv($fh); // get each row
// group them first
foreach($row as $key => $val) {
$data[$key][] = $val;
}
}
$i = 'A';
$xml = new SimpleXMLElement('<groups/>');
foreach($data as $batch) {
$group = $xml->addChild('group', '');
$group->addAttribute('n', $i);
foreach($batch as $value) {
$col = $group->addChild('cols', ' ');
$col->addAttribute('n', 'V');
$col->addChild('col_value', $value);
}
$i++; // increment A -> B -> so on..
}
echo $xml->saveXML();
答
I was thinking something along the lines of:
$file = file('test.csv');
$columnGroups = array();
$columnCount = 0;
foreach($file as $row) {
$rowArray = explode(';',$row);
foreach($rowArray as $column => $cell) {
if(!array_key_exists($column, $columnGroups)) {
$columnGroups[$column] = array();
}
$columnGroups[$column][] = $cell;
}
}
I haven't checked the code yet, but this is the general idea... After this you can put everything in one group at once