CSS代码阻碍了PHP的使用

时间:2018-06-11 12:41:54

标签: php html

我有四个不同类的div,这妨碍了使用PHP。我怎么解决它?

我的代码:

HTML:

<div class="row st_sf_port_container st_sf_wall">
    <div class="st_sf_x1">

    </div>
    <div class="st_sf_x2">

    </div>
    <div class="st_sf_x2">

    </div>
    <div class="st_sf_x1">

    </div>
</div>

我应该这样做:

$data = ["something1", "something2", "something3", "something4"];
<div class="row st_sf_port_container st_sf_wall">
       <?php for($i = 0; $i < sizeof($data); $i++) { ?>
        <div class="st_sf_x1"><!-- here, how could I make like code above -->
            <?php echo $data[$i]; ?>
        </div>
<?php } ?>
    </div>

4 个答案:

答案 0 :(得分:0)

你可以在数组上使用循环,并使用substr()函数找出子字符串,如:

<?php
$data = array("something1", "something2", "something3", "something4");
?>
<div class="row st_sf_port_container st_sf_wall">
<?php
foreach ($data as $elem) {
$iterator = strlen($elem) > 9 ? substr($elem, 9, 1) : 0;
?>
<div class="st_sf_x<?php echo $iterator;?>"><!-- here, how could I make like code above -->
<?php echo $data[$i]; ?>
</div>
<?php
}
?>
</div>

答案 1 :(得分:0)

这里class="st_sf_x<?php echo $i ?>"将改变每次迭代的类名,如st_sf_x1,st_sf_x2等。这样你就可以根据需要为每个类提供不同的css。

 $data = ["something1", "something2", "something3", "something4"];
    <div class="row st_sf_port_container st_sf_wall">
           <?php for($i = 1; $i < sizeof($data); $i++) { ?>
            <div class="st_sf_x<?php echo $i ?>">
                <?php echo $data[$i]; ?>
            </div>
    <?php } ?>
        </div>

答案 2 :(得分:0)

这应该有效,并且可以容纳任何班级组合或订单:

$data = [ 
    ["content" => "something1", "class" => "st_sf_x1"],
    ["content" => "something2", "class" => "st_sf_x2"],
    ["content" => "something3", "class" => "st_sf_x2"],
    ["content" => "something4", "class" => "st_sf_x1"]
];
<div class="row st_sf_port_container st_sf_wall">
   <?php for($i = 0; $i < sizeof($data); $i++) { ?>
    <div class="<?php echo $data[$i]["class"]; ?>">
        <?php echo $data[$i]["content"]; ?>
    </div>
<?php } ?>
</div>

答案 3 :(得分:0)

$data  = ["something1", "something2", "something3", "something4"];
$class = ['st_sf_x1'  , 'st_sf_x2'  , 'st_sf_x2'  , 'st_sf_x1'];
?>
<div class="row st_sf_port_container st_sf_wall">
    <?php for($i = 0; $i < sizeof($data); $i++) { ?>
        <div class="<?php echo $class[$i] ?>">
            <?php echo $data[$i]; ?>
        </div>
    <?php } ?>
</div>