【问题标题】:How to group comma separated values如何对逗号分隔值进行分组
【发布时间】:2014-08-26 08:52:08
【问题描述】:

我想对列中的逗号分隔值进行分组。例如,在下面的数据中,我想将每行的第一个值分组到 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.    

    }
}

【问题讨论】:

    标签: php xml csv simplexml


    【解决方案1】:

    我要做的是首先将它们按列分组,然后创建 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();
    

    【讨论】:

      【解决方案2】:

      我的想法是这样的:

      $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;
          }
      }
      

      我还没有检查代码,但这是一般的想法......之后你可以一次将所有内容放在一个组中

      【讨论】:

        猜你喜欢
        • 2012-04-14
        • 1970-01-01
        • 2016-04-18
        • 2017-06-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-13
        • 1970-01-01
        相关资源
        最近更新 更多