php - 使用模数/循环并放置在每 5 个位置
问题描述
我已经给了自己很多时间来试图解决这个问题 - 没有运气,所以我来这里寻求帮助。
我将如何使用 php 模数运算符并通过数组循环但将数组值放置在每 5 个位置(见下图)
"..." 将从 mysql 查询数组中替换。
查询样本:
$result = $mysqli->query("SELECT id, username, volume, name, content, image, cssanimate, group_name FROM table_1 ");
数组示例:
$my_array = array("Tesla", "BMW", "Ford", "Jeep");
一些代码:
$counter = 0;
while ($row = $result->fetch_assoc()) {
$counter++;
if(($counter % 5 == 0) || $counter==1 ) {
}
}
感谢您的帮助:)
解决方案
一种解决方案:
您可以像这样修改您的代码:
<?php
$my_array = array("Tesla", "BMW", "Ford", "Jeep");
$totalCount = count($my_array); // get the total count of your array
$iteration = $totalCount*5; // multiply as per your iteration
$newArray = array(); // initialize an array
$incArr = 0; // increment for your value's array
for ($i=1; $i <= $iteration; $i++) {
if(($i % 5 == 0) ) { // at every fifth index
$newArray[] = $my_array[$incArr]; // store actual value
$incArr++;
}
else{
$newArray[] = "..."; // store if not a 5th value
}
}
?>
结果:
<?php
$number = 1;
foreach ($newArray as $key => $value) {
echo $number.") ".$value."<br/>";
$number++;
}
?>
应打印为:
1) ...
2) ...
3) ...
4) ...
5) Tesla
6) ...
7) ...
8) ...
9) ...
10) BMW
11) ...
12) ...
13) ...
14) ...
15) Ford
16) ...
17) ...
18) ...
19) ...
20) Jeep
推荐阅读
- java - Selenium (Java) - 根据其他属性获取列表 ID
- python - 如何将包含 null 和非 null 的行分成两个不同的 DataFrame?
- c++ - 是否可以在 C++ 中将参数从“const char []”转换为“char *”?
- ios - 如何设置自定义collectionView Cell Frame?
- google-apps-script - getData 方法返回的最大记录数是多少
- php - 寻找命名空间“安全”,没有找到
- android - 构建风味时如何更改android中的导航抽屉菜单?
- c++ - 从模板化父类中的派生内部类访问受保护的成员变量
- python - Flask 中接收到的图像的形状
- tortoisegit - 如果我必须回滚更改,是否需要在 Git 中创建新分支?