所以我有一个本质上是响应式的代码,它应该并排放置四 (4) 张照片并以随机顺序显示照片。
但是,因为我才刚刚起步,所以我不知道如何创建一个代码来确保在任何给定时间只显示四 (4) 张照片???
因此,根据下面提供的代码,我如何一次只显示四张照片。 (尽管我希望至少有八 (8) 张可能的照片可供它排序。)
使用代码:
<br>
<br>
<h50><?php echo $this->translate('Be Discovered!'); ?></h50>
and connected. Meet anyone & see everything!</a></p>
<br>
<?php
$pics = [
"/public/admin/haleyfoxforabout333.jpg",
"/public/admin/haleyfoxforabout333.jpg",
"/public/admin/team5aboutG333.jpg",
"/public/admin/team6about333.jpg",
"https://www.w3schools.com/w3images/team1.jpg",
"https://www.w3schools.com/w3images/team2.jpg",
"https://www.w3schools.com/w3images/team3.jpg",
"/public/admin/team4_333.jpg"
];
shuffle($pics);
?>
<style>
h50 {
padding: 0 30px 8px;
width: auto;
font-size: 40px;
margin: 0 0 10px 0;
background-color: transparent;
border: none;
border-bottom: 1px solid #D2DBE8;
border-radius: 3px 3px 0 0;
display: inline-block;
}
.headerz {
text-align: center;
padding: 32px;
}
.rowz {
display: -ms-flexbox; /* IE10 */
display: flex;
-ms-flex-wrap: wrap; /* IE10 */
flex-wrap: wrap;
padding: 0 4px;
}
/* Create four equal columns that sits next to each other */
.columnz {
-ms-flex: 25%; /* IE10 */
flex: 25%;
max-width: 25%;
padding: 0 4px;
}
.columnz img {
margin-top: 8px;
vertical-align: middle;
}
/* RL - makes a two column-layout instead of four columns */
@media screen and (max-width: 800px) {
.columnz {
-ms-flex: 50%;
flex: 50%;
max-width: 50%;
}
}
/* RL Takes the two columns stack on top of each other. */
@media screen and (max-width: 600px) {
.columnz {
-ms-flex: 100%;
flex: 100%;
max-width: 100%;
}
}
</style>
<!-- Photo Grid -->
<div class="rowz">
<?php
foreach ($pics as $pic) {
echo '<div class="columnz">';
echo '<img src="' . $pic . '" style="width:100%">';
echo '</div>';
}
?>
</div>
最佳答案
使用array_rand
,它会从你的数组中随机生成keys。第二个参数定义了你想要多少个键:
$keys = array_rand($pics, 4);
foreach ($keys as $key) {
echo $pics[$key];
}
或者你可以切片你打乱的数组:
shuffle($pics);
$pics = array_slice($pics, 0, 4); // reduces your array to 4 elements
或者您可以使用计数器和 break
foreach:
$counter = 0;
foreach($pics as $pic){
if ($counter == 4) {
break;
}
echo $pic;
$counter++;
}
关于php - 写了一个代码来显示随机照片,但在给定时间只需要显示四个 img,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52671968/