2016-11-04 431 views
1

我想建立在PowerShell中一個多維數組是這樣的:PowerShell中添加多維數組

$array[0] = "colours" 
$array[0][0] = "red" 
$array[0][1] = "blue" 
$array[1] = "animals" 
$array[1][0] = "cat" 
$array[1][0] = "dog" 

這裏是我的嘗試:

$array = @() 
$array += "colours" 
$array += "animals" 

$array[0] # outputs "colours" 
$array[1] # outputs "animals" 

$array[0] = @() 
$array[1] = @() 

$array[0] += "red" 
$array[0] += "blue" 
$array[1] += "cat" 
$array[1] += "dog" 

$array[0] # outputs "red", "blue" - i expected "colours" here 
$array[0][0] # outputs "red" 

我明白任何提示。

在此先感謝

回答

3

不能做你試圖用一個嵌套陣列做什麼:

$array = @() 
$array += "colours" 

使得$array[0]包含字符串colours, 但你再通過將空數組分配給$array[0]替換該值:$array[0] = @()。與此同時,您的colours值爲已不存在

您稍後使用字符串redblue填充該數組,以便$array[0]最終包含一個2元素字符串數組@('red', 'blue')


一種選擇是使用哈希表作爲頂級數組的元素類型:

$array = @() 
$array += @{ name = 'colours'; values = @() } 

$array[0].values += 'red' 
$array[0].values += 'blue' 

$array[0].name # -> 'colours' 
$array[0].values # -> @('red', 'blue') 
2

它看起來像你會用[hashtable]更好(也稱爲關聯陣列):

$hash = @{ 
    colours = @('red','blue') 
    animals = @('cat','dog') 
} 

$hash.Keys # show all the keys 

$hash['colours'] # show all the colours 
$hash.colours # same thing 

$hash['colours'][0] # red 

$hash['foods'] = @('cheese','biscuits') # new one 
$hash.clothes = @('pants','shirts') #another way 

$hash.clothes += 'socks'