![](/img/trans.png)
[英]How to group comma separated values into distinct sorted comma separated values
[英]How to group comma separated values
我想在列中用逗号分隔值。 例如,在以下数据中,我想将每行的第一个值分组到组A中,将第二个分组到组B中,依此类推。 这些值是随机的,目的是生成XML文件。
样本数据:
1,2,3,4,5
3,5,4,6,2
所需的输出:
<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>
我正在尝试:
我正在尝试遵循以下代码,但无法弄清楚如何仅创建一次组,然后将值放入其中,
$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.
}
}
我要做的是首先将它们按列分组,然后创建XML。 样品:
// 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();
我在考虑以下方面:
$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;
}
}
我还没有检查代码,但这是一般的想法...之后,您可以将所有内容一次放入一个组中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.