2012-08-15 222 views
0

PHP新手在这里。我想问一下我的嵌套循环的帮助。我认为我很接近,但我很确定我缺少的是转换或休息或两者兼而有之。我已经搞砸了一段时间,但我只是不能正确地做。这里是代码示例。PHP嵌套循环

<?php $items=array(thing01,thing02,thing03,thing04,thing05,thing06,thing07,thing08,thing09,thing10,thing11,thing12,thing13,thing14,thing15,thing16,thing17,thing18,thing19,thing20,thing21,thing22,thing23,thing24,thing25,thing26,thing27,thing28,thing29,thing30,thing31,thing32); ?> 
<?php $array_count = count($items); ?> 
<?php $item_count = 9; ?> 
<?php $blk_Number = ceil($array_count/$item_count); ?> 
<?php echo "<h3>This list should contain " . $array_count . " items</h3>"; ?> 
<ul> 
<?php 
for ($pas_Number = 1; $pas_Number <= $blk_Number; $pas_Number++) {print "<h3>Start of Block " . $pas_Number . " of 9   items</h3>"; 
for ($key_Number = 0; $key_Number < $item_count; $key_Number++){print "<li>" . $items[$key_Number] . "</li>"; } 
{print "<h3>End of Block " . $pas_Number . " of 9 items</h3>"; } 
} 
; ?> 
</ul> 

这是给我的输出:

此列表应该包含32项

Start of Block 1 of 9 items 
thing01 
thing02 
thing03 
thing04 
thing05 
thing06 
thing07 
thing08 
thing09 
End of Block 1 of 9 items 
Start of Block 2 of 9 items 
thing01 
thing02 
thing03 
thing04 
thing05 
thing06 
thing07 
thing08 
thing09 
End of Block 2 of 9 items 
Start of Block 3 of 9 items 
thing01 
thing02 
thing03 
thing04 
thing05 
thing06 
thing07 
thing08 
thing09 
End of Block 3 of 9 items 
Start of Block 4 of 9 items 
thing01 
thing02 
thing03 
thing04 
thing05 
thing06 
thing07 
thing08 
thing09 
Start of Block 4 of 9 items 
thing01 
thing02 
thing03 
thing04 
thing05 
thing06 
thing07 
thing08 
thing09 
End of Block 4 of 9 items 

正如你可以看到数组元素的个数是错误的。第2块应包含10-18项,第3块应包含第19-27项,第4块应包含剩余的5项“东西”。我对阵列中所有愚蠢的元素表示歉意,但我想能够清楚地解释我想要做的事情。

回答

2

我想你想使用array_chunk()

foreach (array_chunk($items, 9) as $nr => $block) { 
    echo "Block $nr\n"; 
    foreach ($block as $item) { 
     echo "\t$item\n"; 
    } 
} 
+0

哇...从来不知道array_chunk它完美的工作!谢谢 – 2012-08-15 06:13:15

1

更换

for ($key_Number = 0; $key_Number < $item_count; $key_Number++){print "<li>" . $items[$key_Number] . "</li>"; }

for ($key_Number = 0; $key_Number < $item_count && $key_number + $pas_number * $item_count < $array_count; $key_Number++){print "<li>" . $items[$key_Number + $pas_number * $item_count] . "</li>"; }

目前,你得到的每一个外循环迭代相同的结果,因为你的内部循环不依赖于迭代外环。

+0

感谢艾威尝试它现在 – 2012-08-15 05:53:27

+0

嗯...那个变化导致所有的内部元素消失 – 2012-08-15 06:01:59

+0

@DavidRamirez我固定的输入错误。 – penartur 2012-08-15 06:13:26