2012-08-15 220 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