当前位置: 动力学知识库 > 问答 > 编程问答 >

Alternating row colors in html table from xml datasource with php

问题描述:

I would like to alternate the row color from odd and even from the following xml with php.

 <?php

// load SimpleXML

$books = new SimpleXMLElement('books.xml', null, true);

echo <<<EOF

<table>

<tr>

<th>Title</th>

<th>Author</th>

<th>Publisher</th>

<th>Price at Amazon.com</th>

<th>ISBN</th>

</tr>

EOF;

foreach($books as $book) // loop through our books

{

echo <<<EOF

<tr>

<td>{$book->title}</td>

<td>{$book->author}</td>

<td>{$book->publisher}</td>

<td>\${$book->amazon_price}</td>

<td>{$book['isbn']}</td>

</tr>

EOF;

}

echo '</table>';

?>

How would I do this with php considering my source is XML?

网友答案:

Add a counter, initialize it to zero, increment on each iteration and put different classes in tr depending on the value of $counter%2 (zero or not). (like ($counter%2)?'odd':'even').

网友答案:

Something like this:

for($i=0;$i<6;$i++)
  {
     if($i % 2)
  {
    // even
  }else{
    // odd
  }
}
网友答案:

Here's a simple way.

<?php
// load SimpleXML
$books = new SimpleXMLElement('books.xml', null, true);

echo <<<EOF
<table>
    <tr>
        <th>Title</th>
        <th>Author</th>
        <th>Publisher</th>
        <th>Price at Amazon.com</th>
        <th>ISBN</th>
</tr>

EOF;

$even = true;

foreach($books as $book) // loop through our books
{
    $class = $even ? 'even' : 'odd';
    $even = $even ? false : true;

    echo <<<EOF
    <tr class="$class">
            <td>{$book->title}</td>
            <td>{$book->author}</td>
            <td>{$book->publisher}</td>
            <td>\${$book->amazon_price}</td>
            <td>{$book['isbn']}</td>
    </tr>

EOF;
}
echo '</table>';
?>
分享给朋友:
您可能感兴趣的文章:
随机阅读: