繁体   English   中英

根据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循环中声明键变量,则可以避免使用“计数器”。
  • 如果您使用模数运算符( % ),则可以避免多个条件。 它将第一个数字除以第二个数字,然后输出其余的数字。
  • 通过foreach循环提供将从开始的索引0 ,使得要显示的索引一样大块将包括: 016712 ,和13 $i%6应用于这些键时,输出将为01
  • 由于echo语句中唯一发生变化的是class属性,因此无需重复完整的<div>行。 DRY编程实践规定您只能修改类值的末尾。 为此,我选择了内联条件。

这是您完成所需输出的最佳/最简单方法。

代码:( 演示

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

另外,如果您不担心让所有浏览器都满意,则可以将纯CSS解决方案与nth-child()implode()

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM