Swap 2D array's rows and columns

依然范特西╮ 提交于 2019-11-29 16:49:25

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.

Michael Smith

I had a break from this project for a while, and ended up figuring it out myself:

;Load the first line into an array (for our Count Later)
$columnsCounter = StringSplit($content[1], ",")
;Here we use the row count (from $content) and column count (from $columnsCounter)
;We define an array that is the perfect size for our Menu Items
Dim $MenuItems[$content[0] + 1][$columnsCounter[0] + 1]

; Now we loop through each row and column
For $x = 1 To ($content[0]) - 1
    ;Create an array with the row we are looking at
    $oneRow = StringSplit($content[$x], ",")
    ;now loop through each column
    For $y = 1 To ($columnsCounter[0])
        ;Grab the item we want and add it to our menu items array
        $MenuItems[$x][$y] = $oneRow[$y]
    Next
Next
Milos

Here is CSV to 2D Array example. Credits to Malkey.

#include <array.au3>

Opt("MustDeclareVars", 1)

Dim $sCSV = '"010","2","03"' & @CRLF & _
        '"24","30","20"' & @CRLF & _
        '"txt","bla","toto"'

Local $arr = _CsvToArray2D($sCSV)
_ArrayDisplay($arr)

; Converts CSV format to a 2D array.
Func _CsvToArray2D($sCSV)
    Local $aTmp = StringRegExp($sCSV & @CR, '(\V*)\v{1,2}', 3)
    Local $NumCols[UBound($aTmp)]
    For $x = 0 To UBound($aTmp) - 1
        StringReplace($aTmp[$x], ",", ",")
        $NumCols[$x] = @extended + 1
    Next
    Local $Max = _ArrayMax($NumCols, 1)

    Dim $aArr[UBound($aTmp)][$Max]

    For $i = 0 To UBound($aArr, 1) - 1
        Local $aTemp = StringSplit($aTmp[$i], ",")
        For $j = 0 To $aTemp[0] - 1
            $aArr[$i][$j] = $aTemp[$j + 1]
        Next
    Next
    Return $aArr
EndFunc  ;==>_CsvToArray2D
;========> End of _CsvToArray2D ======================
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!