[英]More elegant solution to this nested loop, anyone?
我有一個php程序,它掃描目錄,目錄中的內容是pdf文件的縮略圖。 縮略圖隨后顯示在表格中,並包含在父網頁的iframe中。 每個縮略圖本身都是一個超鏈接,當單擊時將打開實際的pdf文件。 為了避免出現水平滾動條,表格行中的9張圖像是完美的。 我寫了一個嵌套循環,實際上就像一個自動換行,在其中顯示9張圖像,然后開始另一行。 實際的代碼更多,因此我將其簡化為一個最小的示例。 乍一看似乎幾乎與直覺相反,在外循環的第二行遞減$ i,但它可以工作。 我想知道是否有人有一個更優雅的解決方案?
$ary = array(1,2,3,4,5,6,7,8,9,10);
for ($i=1; $i<(count($ary)+1); $i++) {
$i = $i-1;
for($j=0; $j<9; $j++) {
if ($i === count($ary)) break;
echo ($ary[$i].", ");
$i+=1;
}
echo "<br>";
}
現在完成的代碼,其中$ ndx是數組的計數,$ dir是包含png圖像的掃描目錄,而$ rtDir是保存pdf的目錄:
if ($ndx > 0) {
$tbl = '<div id="draggable" class="ui-widget-content">
<ul>
<table><tr>';
/* place 9 images on one row */
foreach ($myfiles as $index => $image) {
$pdf = basename($image, ".png");
$pdf = $pdf . ".pdf";
$pdf = $rtDir.$pdf;
$tbl .= '<td>
<span class="zoom">
<a href="'.$pdf.'" target="_blank">
<li><img id="pdfthumb'.$index.'" class="myPhotos" alt="pdf'.$index.'" src="'.$dir.$image.'" ></li>
</a>
</span>
</td>';
if ($index % 9 == 8) {
/* end the current row and start a new one */
$tbl.= "</tr></table><br><br><table style='margin-top:-40px'><tr>";
}
}
$tbl .= "</tr></table></ul></div>";
printf($tbl);
unset($myfiles);
}
感謝大家的建議。
因此,您希望每行9張圖像嗎? 通常有兩個邏輯選擇:
備選方案1:您使用array_chunk()
,例如:
$chunks = array_chunk($images, 9);
foreach ($chunks as $chunk) {
foreach ($chunk as $image) {
// image printing goes here
}
echo '<br'>;
}
備選方案2:您使用模運算符,例如:
foreach ($images as $index => $image) {
// images printing goes here
if ($index % 9 == 0) { // or 8, since it's a 0-index array... I don't remember
echo '<br>';
}
}
如果需要的話,我自己主要使用第二個版本,或者我要求我們的一位設計師通過CSS使它適合合適的寬度。 另請注意,如果您的圖片數組具有關聯性,則第二個版本將不起作用。
$b = count( $ary ) - 1 ;
for( $i = 0 ; $i <= $b ; $i++ ) :
echo $ary[$i] ;
if( ( $i + 1 ) % 9 == 0 ) :
echo "<br>" ;
endif ;
endfor ;
像上面的評論一樣,我喜歡模數,但我也喜歡for循環,希望這會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.