首页 > 解决方案 > 使用模数/循环并放置在每 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

解决方案


一种解决方案:

您可以像这样修改您的代码:

<?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

推荐阅读