使用模数/循环并放置在每第 5 个位置

我花了很多时间试图解决这个问题 - 运气不好,所以我来这里寻求帮助。

我将如何使用 php 模数运算符并循环遍历数组但将数组值放置在每第 5 个位置(见下图)

“...”将从 mysql 查询数组中替换。

查询示例:

$result = $mysqli->query("SELECT id, username, volume, name, content, image, cssanimate, group_name FROM table_1 ");

希望这张图能说明:

http://img3.mukewang.com/618f9c3d000172d101130410.jpg

数组示例:

$my_array = array("Tesla", "BMW", "Ford", "Jeep");


一些代码:


$counter = 0;

while ($row = $result->fetch_assoc()) {

    $counter++;

    if(($counter % 5 == 0) || $counter==1 ) { 


    }


}

感谢您的帮助:)


SMILET
浏览 121回答 1
1回答

慕哥6287543

一种解决方案:您可以像这样修改代码:<?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 arrayfor ($i=1; $i <= $iteration; $i++) {&nbsp;&nbsp; &nbsp; if(($i % 5 == 0) ) {&nbsp; // at every fifth index&nbsp; &nbsp; &nbsp; &nbsp; $newArray[] = $my_array[$incArr]; // store actual value&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; $incArr++;&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp; &nbsp; else{&nbsp; &nbsp; &nbsp; &nbsp; $newArray[] = "..."; // store if not a 5th value&nbsp; &nbsp; }}?>结果:<?php$number = 1;foreach ($newArray as $key => $value) {&nbsp; &nbsp; echo $number.") ".$value."<br/>";&nbsp; &nbsp; $number++;}?>沙盒:应打印为:1) ...2) ...3) ...4) ...5) Tesla6) ...7) ...8) ...9) ...10) BMW11) ...12) ...13) ...14) ...15) Ford16) ...17) ...18) ...19) ...20) Jeep
打开App,查看更多内容
随时随地看视频慕课网APP