簡體   English   中英

如何將逗號分隔的值分組

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM