0

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 个“东西”。我为数组中的所有愚蠢元素道歉,但我希望能够清楚地解释我想要做什么。

4

2 回答 2

2

我想你想使用array_chunk()

foreach (array_chunk($items, 9) as $nr => $block) {
    echo "Block $nr\n";
    foreach ($block as $item) {
        echo "\t$item\n";
    }
}
于 2012-08-15T06:07:47.257 回答
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>"; }

目前,您在每个外循环迭代中都得到相同的结果,因为您的内循环不依赖于外循环的迭代。

于 2012-08-15T05:49:36.873 回答