duan1227 2014-08-26 08:52
浏览 30
已采纳

如何对逗号分隔值进行分组

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.    

    }
}
  • 写回答

2条回答 默认 最新

  • douzhuo6931 2014-08-26 09:07
    关注

    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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了
  • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
  • ¥188 需要修改一个工具,懂得汇编的人来。
  • ¥15 livecharts wpf piechart 属性
  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了