Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
924 views
in Technique[技术] by (71.8m points)

csv - Swap 2D array's rows and columns

I need to get columns from a CSV file into an array (multidimensional array or array of arrays). I used CSV.au3 which loads the rows just fine, but I need the columns in that place. My CSV file looks like:

Item 1, Item 2, Another Item
Item 3, Item 4

It creates a multidimensional array that looks like:

$aResult[0] = [0] => 'Item 1', [1] => 'Item 2', [2] => 'Another Item'
$aResult[1] = [0] => 'Item 3', [1] => 'Item 4'

Where I would like it to look like:

$aResult[0] = [0] => 'Item 1', [1] => 'Item 3'
$aResult[1] = [0] => 'Item 2', [1] => 'Item 4'
$aResult[2] = [0] => 'Another Item'

For each row it should contain the column not the row.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Transpose array

… it should contain the column not the row.

As per Documentation - Function Reference - _ArrayTranspose() :

Transposes a 1D or 2D array (swaps rows and columns)

CSV file to array

… get the Columns in CSV file and load them into an array …

CSV file to 2-dimensional array, as per Documentation - Function Reference - _FileReadToArray() :

Reads the specified file into a 1D or 2D array

Example:

#include <File.au3> ; _FileReadToArray() and $FRTA_NOCOUNT
#include <Array.au3>; _ArrayDisplay()

Global Const $g_sFileCSV         = 'C:file.csv'
Global Const $g_sDelimiterColumn = ','

Global       $g_aCSV

_FileReadToArray($g_sFileCSV, $g_aCSV, $FRTA_NOCOUNT, $g_sDelimiterColumn)

If @error Then    
    ConsoleWrite('_FileReadToArray() error: ' & @error & @LF)    
Else    
    _ArrayDisplay($g_aCSV)    
EndIf

Array to CSV file

_FileWriteFromArray() saves array as text file.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...