I am trying to get some data from Magento trough php, it works but I need to add multiple collections and now I am stuck. I am just a beginner so please forgive me :-)
I am using below code to get customer details, this works ok.
Now I need to add the customer/address to get the address details to fill the last column with the zipcode, anybody know how to do that?
<?php
function getcustomers() {
/* Magento's Mage.php path
* Mage Enabler users may skip these lines
*/
require_once ("app/Mage.php");
umask(0);
Mage::app("nl");
/* Magento's Mage.php path */
/* Get customer model, run a query */
$collection = Mage::getModel('customer/customer')
//$collection = Mage::getModel('customer/address')
->getCollection()
->addAttributeToSelect('*');
$result = array();
foreach ($collection as $customer) {
$result[] = $customer->toArray();
}
return $result;
}
?>
<html>
<head>
<title>Customers</title>
<style>
table {
border-collapse: collapse;
}
td {
padding: 5px;
border: 1px solid #000000;
}
</style>
</head>
<body>
<table>
<tr>
<td>ID</td>
<td>Lastname</td>
<td>Firstname</td>
<td>Email</td>
<td>Is Active?</td>
<td>Date Created</td>
<td>Date Updated</td>
<td>Website ID</td>
<td>Store ID</td>
<td>Zip Code</td>
</tr>
<?php
$result = getcustomers();
if(count($result) > 0){
foreach($result as $key => $value){
echo "<tr>";
echo "<td>".$value['entity_id']."</td>";
echo "<td>".$value['lastname']."</td>";
echo "<td>".$value['firstname']."</td>";
echo "<td>".$value['email']."</td>";
echo "<td>";
echo $value['is_active'] == 1 ? "Yes" : "No";
echo "</td>";
echo "<td>".$value['created_at']."</td>";
echo "<td>".$value['updated_at']."</td>";
echo "<td>".$value['website_id']."</td>";
echo "<td>".$value['store_id']."</td>";
echo "<td>".$value['zipcode']."</td>";
echo "</tr>";
}
}else{
echo "<tr><td colspan=\"7\">No records found</td></tr>";
}
?>
</table>
</body>
</html>
Just want to say that I'm currently learning Magento, so my answer will not be totally working! I hope it'll help to push you in the right direction.
Just a note, you can just use $customer->getData() to return an array.
Then you can use $customer->getId() to get the id. Which you can then pass into the Address model
foreach($collection as $customer){
// You have an instance of the Customer already, so we can just use a magic get method
$cid = $customer->getId();
// Let's load this customers address, using a chain. Load the model (instantiate the class), then call load with the customer id
// You might want to check the alias on 'customer' to ensure it has address. You can find this in /app/code/core/Mage/Customer/etc/config.xml ln.251
$address = Mage::getModel('customer/address')->load($cid);
// Maybe we should look in here just in case - for debugging
var_dump($address); // or echo get_class($address);
// Here I would try one of the magic setter methods, which map to set<Thing> so you can play with this to see if it'll work
$address->setZipCode('12345');
// Then we should be able to save it, I think, this bit I'm not sure on.
$address->save();
}
As I say, this is just what I've learnt from the Magento U videos over the last week, hope it works!
Related
I am looking for the cleanest way I could do the following.
<?php
function display_data($label, $yes_no, $model) {
$return = "<tr><th><label>".$label."</label></th><td>";
if ($yes_no == '1') { $return .= "Yes"; } else { $return .= "No"; }
$return .= "</td><td>";
if (isset($model)) {
$return .= $model;
}
$return .= "</td></tr>";
return $return;
}
?>
<table>
<thead>
<tr>
<th>Make</th>
<th>Yes/No</th>
<th>Model</th>
</tr>
</thead>
<tbody>
<?php
echo display_data("Ford", $car_form["available"], $car_form["avail_model"]);
echo display_data("Honda", $car_form["available"], $car_form["avail_model"]);
?>
</tbody>
</table>
I want to be able to EDIT the body contents of the table by just clicking on any of them, with say jquery. Changing the value and once I click out of it, it saves with AJAX.
So I should be able to click into any of the Yes/No or Model rows and change them. I'm going to have a lot of data, so I am not sure how to do this in large scale. I just don't want to have to create a individual jquery function, and divs for every single piece of data I have. If anyone can think of a cleaner way, that would be awesome.
Everything I have now, is working correctly, I just have not implemented a CRUD like system into this yet.
I am doing a small personal web portfolio in order to learn web development. I have a list of all the stocks that I have "bought" and I would like to update the price in real-time from yahoo finance. I can already do the price update but I override the table that I display the stocks with a new one that is called using javascript.
I know there must be a cleaner way. I am trying to update the price using javascript but I don't think I am doing everything right.
Here is what I have so far.
Portfolio.php displays all the stocks I have
<?php foreach ($shares as $row): ?>
<tr >
<td><?php echo $row["symbol"];?></td>
<td><?php echo $row["name"];?></td>
<td style="text-align: right;"><?php echo $row["shares"];?></td>
<td id="price" style="text-align: right;">$ <?php echo number_format($row["price"],2);?></td>
<td style="text-align: right;"><?php
$change = number_format($row["change"],2);
echo sprintf( "%+1.2f", $change );
echo " ( ";
echo $row["pct"];
echo " )";
?></td>
<td style="text-align: right;">$ <?php echo $row["dayGain"];?></td>
<td style="text-align: right;">$ <?php echo number_format($row["total"],2);?></td>
</tr>
<?php endforeach; ?>
</table>
<script type="text/javascript" src="../html/js/update.js" ></script>
Then I have update.php which returns all the stock information from yahoo finance as a json
<?php
// configuration
require("../includes/config.php");
//query user's portfolio
$rows = query("SELECT * FROM shares WHERE id = ?", $_SESSION["id"]);
$cash = query("SELECT cash FROM users WHERE id = ?", $_SESSION["id"]);
//create array to store the shares
$shares = array();
//for each of the user info
foreach($rows as $row){
$yql_base_url = "http://query.yahooapis.com/v1/public/yql";
$yql_query = "select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22".$row['symbol']."%22)%0A%09%09";
$env = "env=http%3A%2F%2Fdatatables.org%2Falltables.env";
$yql_full_query = $yql_base_url . "?q=" . $yql_query . "&format=json&" . $env;
$session = curl_init($yql_full_query);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($session);
$stock = json_decode($json);
if($stock->query->results !== false){
$shares [] = array(
"symbol" => $stock->query->results->quote->symbol,
"price" => $stock->query->results->quote->LastTradePriceOnly
);
}
}
$return = array("price" => $shares );
echo json_encode($return);
?>
And the third file is update.js in which I am trying to have javascript
$(document).ready(function(){
function stock() {
$(function() {
$.getJSON('../update.php',function(result){
$("div#price2").html(result.price);
});
});
stock();
setInterval(stock(), 10000);
});
});
If I go directly to update.php I can view the prices as json. I think the problem lies with the update.js file but I cannot figure out what the problem is. I cannot even print Hello from update.js in the price field.
What I am trying to do is display the stocks that I have stored in the database and then update the price using ajax and javascript. Any help would be appreciated. Thanks in advance.
Use php's json functions coupled with a .getJSON to update it... Here's some example code:
// pull_stock_price.php
<?php
$return = array("content" => "New Stock Price: $2000");
json_encode($return);
?>
// Jquery to pull stock price once every 10 seconds:
function stock() {
$(function() {$.getJSON("pull_stock_price.php",function(result){
$("#StockPrice").html(result.content);
});
});
stock();
setInterval(stock, 10000);
// HTML!
<td><div id="StockPrice"></div></td>
What this does: Every 10 seconds the user's browser will pull pull_stock_price.php and will take the content provided from the json and update . You can have pull_stock_price.php pull from the database, curl or really anywhere and format the data how you want it.
I have workable mysql query in PHP file.
It is giving me 3 possible different results in my table on site in one column. They are 'WON', 'LOST', or 'PENDING'.
What i want to achieve further is when there is WON word in those specific cell to be in green background, when query result turns LOST to be red background, when PENDING to be grey.
In which way to do this?
I am newbie in this so couldnt find anser myself online.
Here is code of workable query:
<?
$qry = "
SELECT timelive,match_title,selection,
CASE
WHEN game.result LIKE '' THEN 'PENDING'
WHEN game.result LIKE game.selection THEN 'WON'
WHEN game.result NOT LIKE game.selection THEN 'LOST'
END AS result
FROM game
";
$searchText = "";
if($_REQUEST['search_text']!=""){
$searchText = mysql_real_escape_string($_REQUEST['search_text']);
$qry .=" WHERE game.timelive LIKE '%$searchText%' " .
" OR game.match_title LIKE '%$searchText%' " .
" OR game.selection LIKE '%$searchText%' " .
" OR game.username LIKE '%$searchText%'";
}
$qry .= " ORDER BY timelive DESC";
$obj = new pagination_class($qry,$starting,$recpage);
$result = $obj->result;
?>
and HTML part of code for this part of output on site is this:
<table>
<?if(mysql_num_rows($result)!=0){
$counter = $starting + 1;
while($data = mysql_fetch_array($result)) {?>
<tr>
<td align="center"><? echo $data['username']; ?></TD>
<td align="center"><? echo $data['result']; ?></TD>
</tr>
<?
$counter ++;
} ?>
i need to get this desired formatting described above according to output word in 'result' column.
Thanks.
A couple of options, the brute-force way, in which you simply apply a generated style, or by predefining style classes and applying them based on the output...
In the latter case (most reasonable, IMO), you simply apply the content of $result to the class property:
<td align="center" class="<?php echo $result;?>"><? echo $data['result']; ?></td>
In the first case, you might have something like this:
function getStyleColorForStatus($status) {
if ($status == 'WON') {
return 'Green';
}
else if ($status == 'LOST') {
return 'Red';
}
else if ($status == 'PENDING') {
return 'Grey';
}
return '';
}
<td align="center" style="background-color:<?php echo getStyleColorForStatus($data['result']); ?>"><? echo $data['result']; ?></td>
I'm missing the part, which creates your $data variable.
Just add "game.result" to your $data array. Now in your code, you could do something like this:
<tr>
<td align="center" class="<? echo $data['result'];?>"><? echo $data['username']; ?></TD>
<td align="center"><? echo $data['result']; ?></TD>
</tr>
Now you can work with CSS. Create three classes for LOST, PENDING and WON. Example:
.LOST {
background-color: #F00;
}
Your username field in your table should have a red background, when game.result is "LOST"
Create the following css definitions, if possible in a separate css file:
.won
{
background-color:green;
}
.lost
{
background-color:red;
}
After this, link the css file to your page and finally use jQuery to add/remove the css class depending on the given condition.
You can read more on the following links:
http://api.jquery.com/removeClass/
http://api.jquery.com/addClass/
Assign a css class to your table cell, based on the result, like so:
$tdClass = '';
switch ($data['result']) {
case 'WON':
$tdClass = 'won';
break;
case 'LOST':
$tdClass = 'lost';
break;
case 'PENDING':
$tdClass = 'pending';
break;
}
So obviously, this is your php, in your html you do:
<td class="<?php $tdClass; ?>"><?php echo $data['result']; ?></td>
I would lose the align="center" and use in your css text-align: center; instead. Furthermore, in your css, you'd do:
.won {
background: green;
}
.lost {
background: red;
}
.pending {
background: grey;
}
But instead of green, red, etc. choose the exact color you like.
before echo the result put an condition like
if( $data['result'] == 'WON' ){
echo '<div class="green">' . $data['result'] . '</div>'
}
elseif( $data['result'] == 'LOST' ){
echo '<div class="red">' . $data['result'] . '</div>'
}
elseif( $data['result'] == 'PENDDING' ){
echo '<div class="gray">' . $data['result'] . '</div>'
}
I'm making a search system whereby the user enters data into a text area and when he presses 'enter', the search text is sent to the php search query via javascript so that the page doesn't have to reload.
Javascript:
<script type="text/javascript">
function search(str)
{
if (str=="")
{
document.getElementById("search").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{//IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{//IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("search").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","leaderboard.php?q="+str,true);
xmlhttp.send();
}
</script>
Text input:
<form>
<input type="text" value="search for user" onfocus="if
(this.value==this.defaultValue) this.value='';" onblur="if (this.value!==this.defaultValue) this.value='search for user';" id="search" name="search" style="background-color: white; color: black; border: 1px solid black; font-family: verdana; font-size: 9px; height: 20px; text-align: center;" onchange="search(this.value)">
</form>
PHP:
<?php
$con = mysql_connect('localhost', 'refrigerator', 'XXX');
mysql_select_db('refrigerator');
if($q=$_GET["q"]){
$sql="SELECT * FROM users WHERE username = '".$q."'";
$result = mysql_query($sql);
$User = array(); $Count = array(); $t=0; $i=0;
while($row = mysql_fetch_array($result)){
$User[] = $row['username']; $Count[] = $row['count'];
$t=mysql_num_rows($sql);
}
echo '<tr><td>' .$a. '</td><td>'.$row['username'].'</td><td>'.$row['count'].'</td></tr>';
mysql_close($con);
}
if ($q=!$_GET["q"]){
$User = array(); $Count = array(); $t=0; $i=0;
while($row = mysql_fetch_array($result)){
$User[] = $row['username']; $Count[] = $row['count'];
$t=13;
}
$User[] = $row['username']; $Count[] = $row['count'];
while($i<$t) {
$a = $i + 1;
echo '<tr><td>' .$a. '</td><td>'.$User[$i].'</td><td>'.$Count[$i].'</td></tr>';
$i++;
}
}
?>
The javascript definitely works up to the penultimate line, because the url changes to 'http://localhost/%5bclickphilia%5d/leaderboard.php?search=whatever was searched' but then nothing happens.
I'm very new to this so I might have made a blindingly obvious mistake so don't rule out that possibility :D
Thanks
EDIT:
Here is the full code for the table including the php:
<table border="0" cellspacing="15" padding="0" width="200">
<th><font color="#00FF00">Rank</font></th>
<th><font color="#00FF00">Username</font></th>
<th><font color="#00FF00">Score</font></th>
<?php
$con = mysql_connect('localhost', 'refrigerator', 'XXXX');
mysql_select_db('refrigerator');
if($q=$_GET["q"]){
$sql="SELECT * FROM users WHERE username = '".$q."'";
$result = mysql_query($sql);
$result=mysql_real_escape_string($result);
$User = array(); $Count = array(); $t=0; $i=0;
while($row = mysql_fetch_array($result)){
}
echo '<tr><td>' .$a. '</td><td>'.$row['username'].'</td><td>'.$row['count'].'</td></tr>';
mysql_close($con);
}
if ($q=!$_GET["q"]){
$User = array(); $Count = array(); $t=0; $i=0;
while($row = mysql_fetch_array($result)){
$User[] = $row['username']; $Count[] = $row['count'];
$t=13;
}
$User[] = $row['username']; $Count[] = $row['count'];
while($i<$t) {
$a = $i + 1;
echo '<tr><td>' .$a. '</td><td>'.$User[$i].'</td><td>'.$Count[$i].'</td></tr>';
$i++;
}
}
?>
</table>
I'm sure the inserting the php echo into the table works, because the event for if ($q=!$_GET["q"]) works fine. The data is entered into the table okay.
Well this line here:
document.getElementById("search").innerHTML=xmlhttp.responseText;
doesn't make sense to me. The "search" element is that <input> field. Setting that element's "innerHTML" property may do nothing at all to the page, because "text" input elements are "void" elements and have no content.
Maybe you've got a "search_results" table somewhere? If so, you may have some trouble updating the "middle" of a <table> like that, in IE at least. Try it however and you should be able to mess with that to come up with something.
edit — I'll re-state what I think the problem is: your PHP code seems to be putting together the response to the search in some sort of table form; it's creating <tr> and <td> elements. Those need to go into a <table> somewhere (actually technically a <tbody> but whatever). Exactly how, or even if, you want to refine that, I can't say. What you might try however is to add this to your page:
<div id='search_results'>Results Go Here</div>
and put it just somewhere where it'll show up. Then change your "search()" function so that wherever you're setting "innerHTML", change the "id" you search for to "search_results".
I'm assuming you want to implement a kind of autocomplete.
I think this line:
document.getElementById("search").innerHTML=xmlhttp.responseText;
should be:
document.getElementById("search_result").value=xmlhttp.responseText;
You need to have a search_result table, as Pointy pointed out.
In case you are interested in going the jQuery route, this would be your new code:
function search(str){
if (str != "")
$.get("leaderboard.php", {q : str}, function(r){
$("#search_result").html(r);
});
}
If you want to use the Enter key, I would (again) recommend jQuery because you can accomplish this with a few lines of code, instead of several more with pure JavaScript.
Wow. Hard to know where to begin.
I think you're going to get more help if you give us more of an idea of what you're trying to accomplish. I'm thinking you're trying to build an inline search?
If your URL is changing then the form is getting submitted somehow. Since you're using AJAX that's probably not what you want. Add onSubmit="return false;" to the form element. That may solve your immediate problem. (though I'm not sure that onChange will work right cross browser. See #2)
Look at jQuery for AJAX and for DOM manipulation. It's a lot easier than what you're trying to build it using the native tools.
Your query won't work and it's a security problem. Right now anyone can send SQL commands in your q parameter and depending on permissions probably do whatever they want with your database. Look at mysql_real_escape_string() or better yet look at a database framework that uses place holders such as PDO. As for the query itself you're only going to find people with the exact match. You probably want to use LIKE rather than equals.
Here's a PHP example of mine. Can anyone find a shorter/easier way to do this?
<? foreach($posts as $post){?>
<div class="<?=($c++%2==1)?‘odd’:NULL?>">
<?=$post?>
</div>
<? }?>
<style>
.odd{background-color:red;}
</style>
Examples in other languages would be fun to see as well.
Fundamentally - no. That's about as easy as it gets. You might rewrite it a bit shorter/cleaner, but the idea will be the same. This is how I would write it:
$c = true; // Let's not forget to initialize our variables, shall we?
foreach($posts as $post)
echo '<div'.(($c = !$c)?' class="odd"':'').">$post</div>";
If you'd like to have less in-line PHP, a great way of doing it is via JavaScript.
Using jQuery, it's simply:
<script type="text/javascript">
$('div:odd').css('background-color', 'red');
</script>
Using CSS3 you can do something like this:
div:nth-child(odd)
{
background-color: red
}
But better not use that for a few years if you actually want your users to see the color...
Smarty has it inbuilt:
{section name=rows loop=$data}
<tr class="{cycle values="odd,even"}">
<td>{$data[rows]}</td>
</tr>
{/section}
So does Django:
{% for o in some_list %}
<tr class="{% cycle 'row1' 'row2' %}">
...
</tr>
{% endfor %}
i always name my zebra rows "row0" and "row1" - this makes the code a bit simpler.
<?php // you should always use the full opening tag for compatibility
$i = 0;
foreach ($rows as $row) {
echo '<tr class="row' . ($i++ % 2) . '">...</tr>';
}
?>
Maybe a function with a static variable?
<?php
function alternate_row_color($css_class) {
static $show = true;
$show = !$show;
if ($show) {
return $css_class;
} else {
return NULL;
}
}
?>
Then to use it (using your example):
<?php foreach($posts as $post) { ?>
<div class="<?=alternate_row_color('odd')?>">
<?=$post?>
</div>
<?php } ?>
<?php $alt = true; foreach ($posts as $post): $alt = !$alt; ?>
<div<?php echo $alt ? ' class="odd"' : ''; ?>>
<!-- Content -->
</div>
<?php endforeach ?>
Would be the simplest and clearest way to do it.
You can encapsulate the logic as follows:
<?php
class ListCycler {
private $cols, $offs, $len;
// expects two or more string parameters
public function __construct() {
$this->offs = -1;
$this->len = func_num_args();
$this->cols = func_get_args();
foreach($this->cols as &$c)
$c = trim(strval($c));
}
// the object auto-increments every time it is read
public function __toString() {
$this->offs = ($this->offs+1) % $this->len;
return $this->cols[ $this->offs ];
}
}
?>
<html>
<head>
<style>
ul#posts li.odd { background-color:red; }
ul#posts li.even { background-color:white; }
</style>
</head>
<body>
<div>
<h3>Posts:</h3>
<ul id="posts"><?php
$rc = new ListCycler('odd','even');
foreach($posts as $p)
echo "<li class='$rc'>$p</li>";
?></ul>
</div>
</body>
</html>
Just for fun
Assuming you can use CSS3 selectors you can do something like
<div class="posts">
<? foreach($posts as $post){?>
<div>
<?=$post?>
</div>
<? }?>
</div>
<style>
div.posts div:odd{background-color:red;}
</style>
Even with CSS2 support and mootools (javascript library) you can substitute the style with this javascript
<script type="text/javascript">
// obviously this script line should go in a js file in a onload (or onDomReady) function
$$('div.posts div:odd').setStyle('background-color','red');
</script>
If you don't have anything but php a it you can simplify a bit yous code using an array
<? $isodd=array('','odd');
$c=0;
foreach($posts as $post){?>
<div class="<?=$isodd[$c++%2]?>">
<?=$post?>
</div>
<? }?>
It's short enough as it is, but I would probably wrap it into some helper function with a clear name. That way it's more obvious what's going on and you won't have to repeat that logic in all templates where you need it.
If you want to do it on the display end and are comfortable with or otherwise already using javascript, libraries like jQuery will often have :odd and :even selectors, which you can then hook up to adding specific style properties or hooking into CSS more generally by adding classes.
On a side noe, to alternate between two values a and b, a nice way of doing it in a loop is this:
x = a;
while ( true ) {
x = a + b - x;
}
You can also do this without addition and subtraction:
x = a ^ b ^ x;
where ^ is the XOR operation.
If you just want to alternate between 0 and 1, you can do this:
x = 0;
while ( true ) {
x = !x;
}
You could of course use x as an index of colors, CSS style classes and so on.
function row_color($cnt,$even,$odd) {
echo ($cnt%2) ? "<tr bgcolor=\"$odd\">" : "<tr bgcolor=\"$even\">";
}
How to use:
$cnt=0;
while ($row = mysql_fetch_array ($result)) {
row_color($cnt++,"e0e0e0","FFFFFF");
}
You can abuse the $GLOBAL scope to store the current selected class state, see below table_row_toggle() function. Yes, I know its dirty to abuse the $GLOBAL scope, but hey, we're here to fix problems ain't we? :)
Calling the table row toggle function in HTML:
<tr <? table_row_toggle(); ?>>
The function in PHP:
/* function to toggle row colors in tables */
function table_row_toggle() {
/* check if $trclass is defined in caller */
if(array_key_exists('trclass', $GLOBALS)) {
$trclass = $GLOBALS['trclass'];
}
/* toggle between row1 and row2 */
if(!isset($trclass) || $trclass == 'row2') {
$trclass = 'row1';
} else {
$trclass = 'row2';
}
/* set $trclass in caller */
$GLOBALS['trclass'] = $trclass;
/* write the desired class to the caller */
echo ' class="' . $trclass . '"';
}
<?php ($i%2==1) ? $bgc='#999999' : $bgc='#FFFFFF'; ?>
'<div bgcolor=" bgcolor='.$bgc.'">';
Spot on Vilx but, always go minimal for speed (page weight)
<tr class="'.(($c = !$c)?'odd':'even').'">
Been using something like this:
<?php
function cycle(&$arr) {
$arr[] = array_shift($arr);
return end($arr);
}
$oddEven = array('odd', 'even');
echo cycle($oddEven)."\n";
echo cycle($oddEven)."\n";
echo cycle($oddEven)."\n";
A simple little function that works well for me.
<?php
class alternating_rows()
{
private $cycler = true;
//------------------------------------------------------------------------------
function rowclass($row0,$row1)
{
$this->cycler = !$this->cycler;//toggle the cycler
$class=($this->cycler)?$row0:$row1;
return $class;
}// end function rowclass
//------------------------------------------------------------------------------
}//end class alternating rows
?>
<?php $tablerows= new alternating_rows();?>
<table>
<tr>
<th scope="col">Heading 1</th>
<th scope="col">Heading 2</th>
</tr>
<?php foreach ($dataset as $row){?>
<tr class="<?php echo $tablerows->rowclass("oddrow","evenrow"); ?>">
<td>some data</td>
<td>some more data</td>
</tr>
<?php } //end foreach?>
</table>
In PHP I am using this code:
function alternate($sEven = "even", $sOdd = "odd")
{
static $iCount;
return ($iCount++ & 1) ? $sOdd :$sEven;
}
for($i = 0; $i< 5; $i++)
echo alternate();
/*output:
even
odd
even
odd
even
*/
Source: http://sklueh.de/2013/11/einfache-alternierung-mit-php/