1

我需要将 CSV 文件中的列放入数组(多维数组或数组数组)。我使用CSV.au3加载就好了,但我需要那个地方的。我的 CSV 文件如下所示:

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

它创建了一个多维数组,如下所示:

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

我希望它看起来像:

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

对于每一行,它应该包含列而不是行。

4

3 回答 3

1

转置数组

…它应该包含列而不是行。

根据文档 - 功能参考 -_ArrayTranspose()

转置一维或二维数组(交换行和列)

CSV 文件到数组

… 获取 CSV 文件中的列并将它们加载到数组中…

根据文档 - 函数参考 -_FileReadToArray()将 CSV 文件转换为二维数组:

将指定文件读入一维或二维数组

例子:

#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

数组到 CSV 文件

_FileWriteFromArray()将数组保存为文本文件。

于 2017-09-21T14:56:34.033 回答
0

这是 CSV 到 2D 数组的示例。归功于马尔基

#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 ======================
于 2013-10-28T00:09:45.977 回答
0

我从这个项目中休息了一段时间,最终自己弄清楚了:

;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
于 2014-10-28T08:47:30.413 回答