使用PHP比较表中不同行的单元格值

时间:2014-08-08 22:28:54

标签: php html-table

我的问题类似于此处发现的问题:

compare values of cells in different rows in table using jquery

使用PHP,将行和单元格组合在一起的最佳方法是什么 - 如果第一列中的值和第3列的值相同,同时保持斑马条纹图案?

这就是我尝试做的事:http://jsfiddle.net/zmcjwqk9/

<table border="1">
<thead>
    <tr>
        <td>TITLE A</td>
        <td>TITLE B</td>
        <td>TITLE C</td>
    </tr>
</thead>
<tbody>
    <tr style="background-color: yellow">
        <td>A</td>
        <td>B</td>
        <td>C</td>
    </tr>
    <tr style="background-color: red">
        <td>AA</td>
        <td>BB</td>
        <td>CC</td>
    </tr>
    <tr style="background-color: yellow">
        <td>AAA</td>
        <td>BBB</td>
        <td>CCC</td>
    </tr>
    <tr style="background-color: yellow">
        <td>AAA</td>
        <td>BBBB</td>
        <td>CCC</td>
    </tr>
    <tr style="background-color: red">
        <td>AA</td>
        <td>BBB</td>
        <td>CC</td>
    </tr>
    <tr style="background-color: yellow">
        <td>A</td>
        <td>B</td>
        <td>C</td>
    </tr>
    <tr style="background-color: red">
        <td>AA</td>
        <td>BB</td>
        <td>CC</td>
    </tr>
    <tr style="background-color: red">
        <td>AA</td>
        <td>BBB</td>
        <td>CC</td>
    </tr>
    <tr style="background-color: yellow">
        <td>AAAA</td>
        <td>BBBB</td>
        <td>CCCC</td>
    </tr>
    <tr style="background-color: yellow">
        <td>AAAA</td>
        <td>BBB</td>
        <td>CCCC</td>
    </tr>
    <tr style="background-color: yellow">
        <td>AAAA</td>
        <td>BB</td>
        <td>CCCC</td>
    </tr>
    <tr style="background-color: red">
        <td>AAA</td>
        <td>BBB</td>
        <td>CC</td>
    </tr>
</tbody>

PHP

 echo '<table class="tableListingTable">
            <thead style="font-size: 2.5em; height: 40px; line-height: 40px; width: 100%;">
                <tr>
                    <td>To</td>
                    <td>Time</td>
                    <td>Airline</td>
                </tr>
            </thead>
            <tbody>';

    foreach ($productPages as $productArray => $v) {
        $class = ($c = !$c) ? 'odd' : 'even';
        echo '<tr class="future ' . $class . '">';
            echo '<td width="16%">' . $v['destinationCity'] . '</td>\n';
            echo '<td width="16%">' . $v['currentTime'] . '</td>\n';
            echo '<td width="16%">' . $v["airlineName"] .'</td>';}
        echo '</tr></tbody></table>';

1 个答案:

答案 0 :(得分:1)

创建表的代码应该是这样的:

$color = 'red';
$prevA = $prevC = null;
foreach ($data as $row) {
    if ($row['A'] != $prevA || $row['C'] != $prevC) {
        $color = $color == 'red' : 'yellow';
        $prevA = $row['A'];
        $prevC = $row['C'];
    }
    echo "<tr class='$color'><td>{$row['A']}</td><td>{$row['B']}</td><td>{$row['C']}</td></tr>";
}