I have two arrays and I want to get array2 number of elements by looping through array1 based on the value of each element of array1
$array1 = @(2,1,3)
[System.Collections.ArrayList]$array2 = "string1",'string2','string3','string4','string5','string6'
for ($i=0; $i -lt $array1.Length; $i ) {
$cod_nr = $array1[$i] - 1
for ($x=0; $x -le $cod_nr; $x ) {
... missing logic ...
Basically here I should get first $array1[-] elements of array2 every run
}
(remove array collected element - maybe this step should be in the for loop above)
missing logic
}
Basically, I want to get the following output: 1st run (get 2 elements [array1[0,1]: $my_variable = "string1, string2"
2nd run (get 1 element $array1[2] - number of the element will change if a element is removed): $my_variable = "string3"
3rd run (get 3 elements $array1[3,4,5] - number of the element will change if a element is removed): $my_variable = "string4, string5, string6"
CodePudding user response:
If we could understand what you're actually trying to solve, the advice will probably be different.
However, for your specific request, here is how I would handle it.
$array1 = 2,1,3
[System.Collections.ArrayList]$array2 = "string1",'string2','string3','string4','string5','string6'
foreach($element in $array1){
$my_variable = $array2[0..($element - 1)]
Write-Host my_variable contains $my_variable
$array2.RemoveRange(0,$element)
}
Since you always want the first X elements, it's rather easy. Just grab those and then remove them. No need to use a for loop.
Output
my_variable contains string1 string2
my_variable contains string3
my_variable contains string4 string5 string6