Jump to content

[SOLVED] o so simple, nesting arrays question


Lodius2000

Recommended Posts

i think this will be a softie

 

I have an array called $styles

and an array called $row

$row has a numeric value called id

I need to do some math with id and make the result of that math determine the value of the key to the $styles array

 

heres my shot

 

$styles[$row[id % 2]]

 

$styles should have 2 values because of that, 0 and 1

those become the keys to the array to determine which element of the style array to use, the value of 0 or 1

 

so is nesting attempt correct?

Link to comment
Share on other sites

I have no idea where you got your code from. When I do zebra stripes, it's unrelated to the query's array. I do...

 

$n = 0;
while($row = mysql_fetch_assoc($result))
{
  extract($row);
  if($n%2 == 0) $bgcolor="whatever color";
  else $bgcolor="other color";
  echo "<td bgcolor=$bgcolor>text</td>";

}

 

and modify as needed. This is provided you only need alternating colors. If you're looking for different colors based on the content, let us know.

Link to comment
Share on other sites

I have no idea where you got your code from. When I do zebra stripes, it's unrelated to the query's array. I do..

 

Just to fix your code before I comment, your not incrementing the $n variable....

 

$n = 0;
while($row = mysql_fetch_assoc($result))
{
  extract($row);
  if($n%2 == 0) $bgcolor="whatever color";
  else $bgcolor="other color";
  echo "<td bgcolor=$bgcolor>text</td>";
  $n++;
}

 

The op's method relies on each row having odd/even numbers in sequence. Your method relies on the $n variable being incremented one number (odd followed by even) at a time.

 

$styles = array('ddd','eee');

if ($result = mysql_query("SELECT id,data FROM foo")) {
  if (mysql_num_rows($result)) {
    while($row = mysql_fetch_assoc($result)) {
      echo "<td bgcolor='" . $styles[$row['id'] % 2] . "'>" . $row['data'] . "</td>";
    }
  }
}

 

The first method is obviously more reliable as there is no guarantee that the id field will contain odd/even increments.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.