我有一个包含7个项目的对象。
$obj.gettype().name
Object[]
$obj.length
7我不想使用模数函数,我只想创建一个只有3个项目的新对象。伪代码:
$j=0
$k=1
for($i=0;$i<$obj.length;$i+=3){
$j=$i+2
$myTmpObj = $obj[$i-$j] # create tmpObj which contains items 1-3, then items 4-6, then 7 etc
echo "Batch $k
foreach($item in $myTmpObj){
echo $item
}
$k++
}
Batch 1
item 1
item 2
item 3
Batch 2
item 4
item 5
item 6
Batch 3
Item 7你好,泰德
发布于 2011-05-14 14:15:12
您的伪代码几乎是真实的。我刚刚更改了它的语法并使用了范围运算符(..):
# demo input (btw, also uses ..)
$obj = 1..7
$k = 1
for($i = 0; $i -lt $obj.Length; $i += 3) {
# end index
$j = $i + 2
if ($j -ge $obj.Length) {
$j = $obj.Length - 1
}
# create tmpObj which contains items 1-3, then items 4-6, then 7 etc
$myTmpObj = $obj[$i..$j]
# show batches
"Batch $k"
foreach($item in $myTmpObj) {
$item
}
$k++
}输出看起来完全符合要求。
https://stackoverflow.com/questions/6000030
复制相似问题