php - 编写了一个代码来显示随机照片,但在给定时间只需要显示四个 img
问题描述
所以我有一个本质上是响应式的代码,它应该并排放置四 (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 = 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++;
}
推荐阅读
- reactjs - 如何将 ObjectURL 转换为图像
- android - 可绘制资源文件填充宽度
- python-3.x - 在 VSCode 中使用“重命名符号”时防止创建 .ropeproject
- sql - 统计两个表的外键重复次数
- node.js - 从 react 上传图片到 express
- ubuntu - 如何在 Google Colab 中安装 Anaconda
- python - 如何从 Python 中的 Dictionary 中的值中过滤掉 None?
- swift - @Published 需要 willSet 触发
- loops - 批处理文件找不到要处理的文件
- regex - nginx 使用地图重定向多个 URL