Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
678 views
in Technique[技术] by (71.8m points)

php: how to add odd/even loop in array

here is my code: http://www.pcgage.net/code.zip (sorry, pasting the code caused it to really mess up, even using the code container).

Scroll to line: 160 (to 174) - this is the loop in question. i want to make it so this is the even part, and then some code to make an odd part, so the loop repeats in this order. The reason is that i want to change the content of this loop alternately.

I am not a coder, so the best thing you could do is to post up the new code and i'll add it in where you tell me too, otherwise i'll get lost :)

Hope that makes sense, if not you can check an earlier post about this issue that explains why i need this (after finding out that css alone cannot solve my problem): css/php: how to solve this div float problem / odd even loop in array

this is the loop:

} elseif ( ( $findpost->ID ) != $id ) {

// all other posts except the current post

                    $serp_list_li[] = '<div class="serial-contain">

<div class=""><h5><a href="' . get_permalink($findpost->ID) . '" title="' . $findpost->post_title . '">' .  $findpost->post_title . '</a></h5></div>

<div class="text-align">' .  $findpost->post_excerpt . ' </div>

<div class="date"> ' . mysql2date('M jS, Y', $findpost->post_date) . ' at ' . mysql2date('g:ia', $findpost->post_date) . '</div>


<div class="comments"><a href="' . get_permalink($findpost->ID) . '#comments" title="' . $findpost->post_title . '"><b>' .  $findpost->comment_count . ' Comments</b></a></div>


</div>' . "
";
                } 



else {              
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The three ways are

Modulo

for ($i = 0; $i < 10; $i++)
{
  if ($i % 2 == 0)
  {
    echo "even";
  }
  else
  {
    echo "odd";
  }
}

Flipping boolean value

$even = true;
for ($i = 0; $i < 10; $i++)
{
  if ($even)
  {
    echo "even";
  }
  else
  {
    echo "odd";
  }

  $even = !$even;
}

And mentioned boolean operator

for ($i = 0; $i < 10; $i++)
{
  if ($i & 1 == 0)
  {
    echo "even";
  }
  else
  {
    echo "odd";
  }
}

The most fastest is boolean operator. But the most robust is flipping method if you have very different numbers (like running through ID numbers and some are missing).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...