使用php在xml数据源的html表格中交替使用行颜色
我想用php替换以下xml中的奇数和偶数行颜色使用php在xml数据源的html表格中交替使用行颜色,php,Php,我想用php替换以下xml中的奇数和偶数行颜色 <?php // load SimpleXML $books = new SimpleXMLElement('books.xml', null, true); echo <<<EOF <table> <tr> <th>Title</th> <th>Author</th&g
<?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>';
?>
添加一个计数器,将其初始化为零,在每次迭代中递增,并根据$counter%2
的值(零或否)将不同的类放入tr
。(比如($counter%2)?“奇数”:“偶数”
。比如:
for($i=0;$i<6;$i++)
{
if($i % 2)
{
// even
}else{
// odd
}
}
对于($i=0;$i),这里有一个简单的方法
<?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>';
?>