Reputation: 37
I'm stuck.
I would like to create a multidim array with the following structure
$x[index]['word']="house"
$x[index]['number']=2,5,7,1,9
where index is the first dimension from 0 to... n
second dimension has two fields "word" and "number"
and each of these two fields holds an array (the first with strings, the second with numbers)
I do not know how to declare this $x
I've tried with
$x = @(()),@(@()) - doesn't work
or
$x= ("word", "number"), @(@()) - doesn't work either
or
$x = @(@(@(@()))) - nope
Then I want to use this array like this:
$x[0]["word"]= "bla bla bla"
$x[0]["number]= "12301230123"
$x[1]["word"]= "lorem ipsum"
$x[2]["number]=...
$x[3]...
$x[4]...
The most frequent errors are
Array assignment failed because index '0' was out of range.
Unable to index into an object of type System.Char/INt32
I would like to accomplish this using arrays[][]
or jaws @ but no .net [,] stuff.
I think I'm missing something.
Upvotes: 1
Views: 2080
Reputation: 54821
If I understood you correctly, you're looking for an array of hashtables. You can store whatever you want inside an object-array, so store hashtables that you can search with words or numbers as keys. Ex:
$ht1 = @{}
$ht1["myword"] = 2
$ht1["23"] = "myvalue"
$ht2 = @{}
$ht2["1"] = 12301230123
$arr = @($ht1,$ht2)
PS > $arr[1]["1"]
12301230123
PS > $arr[0]["myword"]
2
PS > $arr[0]["23"]
myvalue
If you know how many you need, you can use a shortcut to create it:
#Create array of 100 elements and initialize with hashtables
$a = [object[]](1..100)
0..($a.Length-1) | % { $a[$_] = @{ 'word' = $null; 'number' = $null } }
#Now you have an array of 100 hastables with the keys initialized. It's ready to recieve some values.
PS > $a[99]
Name Value
---- -----
number
word
And if you need to add another pair later, you can simply use:
$a += @{ 'word' = $yourwordvar; 'number' = $yournumbervar }
Upvotes: 1
Reputation: 5504
You could make an array, and initialize it with hashtables:
$x=@(@{})*100;
0..99 | foreach {$x[$_]=@{}};
$x[19]["word"]="house";
$x[19]["number"]=25719;
You want a big array, for example of length 100. Note the difference in parentheses!
You need the second step, because in the previous command the pointer of the hashtable was copied 100 times... and you don't want that :)
Now test it:
$x[19]["number"];
25719
$[19]["word"];
house
Upvotes: 0