根据 php 中的条件循环数组

Loop an array based on condition in php

我需要帮助来构建基于数组循环的 HTML div。

我的数组如下所示

$myarray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18];

PHP 文件看起来像

<?php
foreach ($myarray as $arr) {
    //I dont know how to add condition here
    echo "<div class='custom_style'>" . $arr ."</div>";
}

我的输出应该是这样的

让我解释清楚。最初,我希望前 2 个数组键是大尺寸,然后接下来的 4 个是小尺寸。同样,下一个 2 将变大,下一个 4 将变小..依此类推..我想以这种方式循环直到我的数组结束。

请忽略CSS part.i自己写

我为您的动态框编写了逻辑,现在您需要创建您的 css。

<html>
<style>
#cust_1
{
    border: 1px solid red; 
    min-width:90px; 
    min-height:90px; 
    display: inline-block;
}

#cust_2
{
    border: 1px solid red; 
    min-width:40px; 
    min-height:40px; 
    display: inline-block;
}
</style>
<?php
$myarray = array(1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12);
$i = 1;

foreach ($myarray as $arr)
 {

     if($i <= 2){
        echo "<div id=cust_1>". $arr . "</div>";
        $i++;
     }
    else if($i==6){ 
            $i=1;
        echo "<div id=cust_2>". $arr . "</div>";
    }else{
        echo "<div id=cust_2>". $arr . "</div>";
        $i++;
    }
 }
?>
  • 如果您只在 foreach 循环中声明键变量,则可以避免使用 "counters"。
  • 如果您利用取模运算符 (%),则可以避免多重条件。它将第一个数字除以第二个数字并输出余数。
  • foreach 循环提供的索引将从0开始,因此您希望显示为大块的索引将包括:01671213。当 $i%6 应用于这些键时,输出将是 01.
  • 因为我们的 echo 语句中唯一改变的是 class 属性,所以没有必要重复完整的 <div> 行。 DRY 编程实践规定您只能修改 class 值的末尾。为此,我选择了内联条件。

这是您实现所需输出的best/simplest方法。

代码:(Demo)

$myarray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18];
foreach ($myarray as $i=>$v){
    echo "<div class=\"cust",($i%6<2?1:2),"\">$v</div>\n";
}

输出:

<div class="cust1">1</div>
<div class="cust1">2</div>
<div class="cust2">3</div>
<div class="cust2">4</div>
<div class="cust2">5</div>
<div class="cust2">6</div>
<div class="cust1">7</div>
<div class="cust1">8</div>
<div class="cust2">9</div>
<div class="cust2">10</div>
<div class="cust2">11</div>
<div class="cust2">12</div>
<div class="cust1">13</div>
<div class="cust1">14</div>
<div class="cust2">15</div>
<div class="cust2">16</div>
<div class="cust2">17</div>
<div class="cust2">18</div>

或者,如果您不担心满足所有浏览器,您可以使用 nth-child()implode() 的纯 css 解决方案。

<style> 
div:nth-child(6n+1),div:nth-child(6n+2) {
    background: red;
}
</style>
<?php
$myarray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18];
echo '<div>',implode('</div><div>',$myarray),'</div>';  // glue each value with a closing and opening div tag
?>