我正在尝试创建一个三列Pinterest布局的模拟,该布局扫描图像目录并将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>
答案 0 :(得分: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];
答案 1 :(得分: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";
}
}
}