2013-04-09 78 views
0

我試圖創建一個三列Pinterest佈局的模擬,掃描圖像的目錄並在每個列中放置1/3的圖像。創建三個div,每個包含1/3的內容

但我不知道如何獲得正確的圖像顯示在列中。

所有圖像都包含在內並不重要,我只是希望列看起來適度均勻。

這是我到目前爲止,但顯然這只是列出每個列中的所有圖像。

<?php 
    $dir = 'img'; 
    $files = scandir($dir); 
    $count = round((count($files)/3), 0); 
?> 

<div class="column"> 
    <?php 
     foreach ($files as $file) { // 1/3 of the images 
      if ($file != "." && $file != "..") { 
        echo "<img src=\"img/" . $file . "\">" . "\n"; 
      } 
     } 
    ?> 
</div> 

<div class="column"> 
    <?php 
     foreach ($files as $file) { // 1/3 of the images 
      if ($file != "." && $file != "..") { 
        echo "<img src=\"img/" . $file . "\">" . "\n"; 
      } 
     } 
    ?> 
</div> 

<div class="column"> 
    <?php 
     foreach ($files as $file) { // 1/3 of the images 
      if ($file != "." && $file != "..") { 
        echo "<img src=\"img/" . $file . "\">" . "\n"; 
      } 
     } 
    ?> 
</div> 



更新: 最終我用這個

<?php 
    $dir = 'img'; 
    $files = scandir($dir); 
    $count = round((count($files)/3), 0); 
?> 

<div class="column"> 
<?php 
    // 1/3 of the images 
    for ($i = 0; $i < floor(count($files)/3); $i++) { 
     $file = $files[$i]; 
     if ($file != "." && $file != "..") { 
       echo "<img src=\"img/" . $file . "\">" . "\n"; 
     } 
    } 
?> 
</div> 

<div class="column"> 
    <?php 
     // 2/3 of the images 
     for ($i = floor(count($files)/3); $i < floor(count($files)/3) * 2; $i++) { 
      $file = $files[$i]; 
      if ($file != "." && $file != "..") { 
        echo "<img src=\"img/" . $file . "\">" . "\n"; 
      } 
     } 
    ?> 
</div> 

<div class="column"> 
    <?php 
     // 3/3 of the images 
     for ($i = floor(count($files)/3) * 2; $i < count($files); $i++) { 
      $file = $files[$i]; 
      if ($file != "." && $file != "..") { 
        echo "<img src=\"img/" . $file . "\">" . "\n"; 
      } 
     } 
    ?> 
</div> 

回答

1

我會用for循環,就像這樣:

// 1/3 of the images 
for ($i = 0; $i < floor(count($files)/3); $i++) { 
    $file = $files[$i]; 

// 2/3 of the images 
for ($i = floor(count($files)/3); $i < floor(count($files)/3) * 2; $i++) { 
    $file = $files[$i]; 

// 3/3 of the images 
for ($i = floor(count($files)/3) * 2; $i < count($files); $i++) { 
    $file = $files[$i]; 
0
$num = 0; 
$col = 0; // column number: 0, 1 or 2 
foreach ($files as $file) { // 1/3 of the images 
    if ($file != "." && $file != "..") { 
     if ($num++ % 3 == $col) { 
      echo "<img src=\"img/" . $file . "\">" . "\n"; 
     } 
    } 
} 
相關問題