Search code examples
arrayscsvautoittranspose

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.


Solution

  • 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