我有一个包含7个项目的对象.
$obj.gettype().name
Object[]
$obj.length
7
Run Code Online (Sandbox Code Playgroud)
我想分批循环3.我不想使用模数函数,我实际上希望能够只用该批次中的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
Run Code Online (Sandbox Code Playgroud)
问候,特德
Rom*_*min 10
你的伪代码几乎是真实的.我刚刚更改了它的语法并使用了范围运算符(..):
# 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++
}
Run Code Online (Sandbox Code Playgroud)
输出看起来完全符合要求.
| 归档时间: |
|
| 查看次数: |
1519 次 |
| 最近记录: |