March 8, 2012

xml to php table alternating row color

Question by bignow23

Trying to display an html table from and xml from php, getting error when trying to alternate the row base on even and odd mostly for styling the table.

foreach($bookdata as $book) // loop through our books
{
$i = 0;
        if($i%2 == 0)
   {
      $class = 'even';
   }
   else
   {
      $class = 'odd';
   }

  { 


        echo <<<EOF
        <tbody>
     <tr class='$class'>
                <td>{$book->date} </td>

                <td><a href='http://www.website.com{$book->dataNo}.html'>{$book->Name}</td>
               <td><a href='http://www.website.com/-{$book->authorcodeNo}.html'>{$book->author}</td>


      </tr>
    }
       $i++;
    }


EOF;
}
 echo '</tbody>';
echo '</table>';

Any help most welcome

Answer by Starx

You are reseting the $i to 0 on every loop.

Remove

$i = 0;

from your code. And I didn’t notice this before but the EOF is misplaced. Here is a full working solution

foreach($bookdata as $book) // loop through our books
{
    if($i%2 == 0) { $class = 'even'; }
    else { $class = 'odd'; }
    echo <<<EOF
        <tbody>
            <tr class='$class'>
                <td>{$book->date} </td>
                <td><a href='http://www.website.com{$book->dataNo}.html'>{$book->Name}</td>
               <td><a href='http://www.website.com/-{$book->authorcodeNo}.html'>{$book->author}</td>
            </tr>
EOF;
       $i++;
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!