着色foreach循环表中的每隔一行

时间:2017-08-07 07:00:14

标签: php

我有一个问题,我需要为使用foreach循环生成的表中的每隔一行着色。虽然在while和for是一个简单的平庸,所以在foreach我完全不知道如何采取它。

我把我能够创建的代码,只有一个问题 - 它为所有相同的行着色。

<?php 
        $details = array_combine($_POST['detail'], $_POST['detail-description']);
        foreach($details as $key => $value) {
        $bg = ($i % 2 == 0) ? 'red' : 'yellow';
        ?>
            <tr style="background: <?php echo $bg; ?>;"><td style="padding: 3px 10px; text-align: right; border-right: 1px solid #dbdbdb;" width="50%">
            <?php echo $key ?>
            </td>
            <td style="padding: 3px 10px; text-align: left;" width="50%">
            <?php echo $value; ?>
            </td>
            </tr>
        <?php
        }
        ?>

1 个答案:

答案 0 :(得分:0)

以下代码:

<?php 
$details = array(
    "test1"=>"tester1",
    "test2"=>"tester2",
    "test3"=>"tester3",
    "test4"=>"tester4",
    "test5"=>"tester5",
    "test6"=>"tester6",
    "test7"=>"tester7",
);
$i=0;
foreach($details as $key => $value) {
    $i++;
    $bg=($i%2==0?'red':'yellow');
    ?>
    <table>
        <tr style="background-color: <?php echo $bg; ?>;">
            <td style="padding: 3px 10px; text-align: right; border-right: 1px solid #dbdbdb;" width="50%">
                <?php echo $key ?>
            </td>
            <td style="padding: 3px 10px; text-align: left;" width="50%">
                <?php echo $value; ?>
            </td>
        </tr>
    </table>
    <?php
}
?>

返回:

enter image description here

您需要table代码才能在background-color代码上应用tr

相关问题