我使用以下语句来填充数组:
for ([int]$i=1; $i -lt 4; $i++)
{
for ([int]$j=11; $j -lt 32; $j=$j+10)
{
$myRegularArray += ,($i, $j, [int](($i +1) * $j))
}
}
输出几乎就是您所期望的:
foreach ($row in $myRegularArray)
{
write-host "$($row[0]) rampant frogs, $($row[1]) horny toads & $($row[2]) bottles of beer"
}
1 green frogs, 11 horny toads & 22 bottles of beer
1 green frogs, 21 horny toads & 42 bottles of beer
1 green frogs, 31 horny toads & 62 bottles of beer
2 green frogs, 11 horny toads & 33 bottles of beer
2 green frogs, 21 horny toads & 63 bottles of beer
2 green frogs, 31 horny toads & 93 bottles of beer
3 green frogs, 11 horny toads & 44 bottles of beer
3 green frogs, 21 horny toads & 84 bottles of beer
3 green frogs, 31 horny toads & 124 bottles of beer
但是,我使用 select-object 并且在某些情况下仅从多维数组中选择一行。例如
foreach ($row in ($myRegularArray | where-object { $_[2] -eq 124 }))
{
write-host "$($row[0]) rampant frogs, $($row[1]) horny toads & $($row[2]) bottles of beer"
}
现在,foreach 会迭代数组单维中的每个对象:
3 rampant frogs, horny toads & bottles of beer
31 rampant frogs, horny toads & bottles of beer
124 rampant frogs, horny toads & bottles of beer
我可以理解为什么会发生这种情况,并且我认为答案是不要使用 foreach。我有什么方法可以改变这种行为,以便我仍然可以使用 foreach?
最佳答案
添加 at 符号
foreach ($row in @($myRegularArray | where-object { $_[2] -eq 124 }))
{
write-host "$($row[0]) rampant frogs, $($row[1]) horny toads & $($row[2]) bottles of beer"
}
您的问题是您的 Where-Object
仅匹配一行。如果您匹配的行超过一行,我们就不会注意到。
where-object { $_[2] -gt 60 }
PowerShell 正在展开阵列。使用@
可以确保返回一个数组。
关于arrays - powershell多维数组和foreach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29513496/