0

I have 2 dimension array. I would like to get each value of array. I tried this, but each array in $Name has all the array in $Date. But my expectation first item in $Name equal to first item in $Date. This is my expectation result:

A\11
B\12
C\13

$Name = @("A", "B", "C") #the size of this array not fixed
$Date = @("11", "12", "13") #the size of this array not fixed

foreach ($na in $Name)
{
     foreach ($dt in $Date)
     {
          $NameAndDate = "$na\$dt"
          Write-Host $NameAndDate
     }
}

but from the code above I got this result

A\11
A\12
A\13
B\11
B\12
B\13
C\11
C\12
C\13

Anyone can help, please. Thank you

Cheries
  • 834
  • 1
  • 13
  • 32
  • Does this answer your question? [Perform math operations with two equal length arrays](https://stackoverflow.com/questions/66250643/perform-math-operations-with-two-equal-length-arrays) – iRon Feb 23 '21 at 09:24
  • @iRon no, its not answer my question – Cheries Feb 23 '21 at 09:33
  • are you trying to merge two 1-d arrays into one 2-d array? – Lee_Dailey Feb 23 '21 at 09:54
  • 2
    @SBR - Your question does not make complete sense, Should "B\13" exist in your expected output? - If so you are not fully declaring what logic should determine this, if this is not the case I would advise a for loop: `For ($i = 0; $i -lt $name.count; $i++){ ($Name[$i]) + "\" + ($Date[$i]) }` – CraftyB Feb 23 '21 at 10:02
  • 1
    Please *explain* what you expect as an output. @jfmilner answer returns `A\11 B\12 C\13` what I would guess you would actually expect (and what is described in the duplicate). But in your example script, you have `A\11 B\12 B\13 C\13` in top, is that what you expect as an output? If yes, please explain where where the `B\13` is coming from. – iRon Feb 23 '21 at 10:05
  • Thank you all, all the answers are awesome!! Appreciated! – Cheries Feb 24 '21 at 03:09

2 Answers2

1

Try this

$Name = @("A", "B", "C") #the size of this array not fixed
$Date = @("11", "12", "13") #the size of this array not fixed
foreach ($i in 0..($Name.Count -1)) {
    write-host ($Name[$i] + "\" + $Date[$i])
}
jfrmilner
  • 1,458
  • 10
  • 11
1

When combining two arrays, both having a non-fixed number of elements, you need to make sure you do not index beyond any of the arrays indices.

The easiest thing here is to use an indexed loop, where you set the maximum number of iterations to the minimum number of array items:

$Name = "A", "B", "C"    # the size of this array not fixed
$Date = "11", "12", "13" # the size of this array not fixed

# make sure you do not index beyond any of the array indices
$maxLoop = [math]::Min($Name.Count, $Date.Count)

for ($i = 0; $i -lt $maxLoop; $i++) {
    # output the combined values
    '{0}\{1}' -f $Name[$i], $Date[$i]
}

Output:

A\11
B\12
C\13
Theo
  • 57,719
  • 8
  • 24
  • 41