php:如何在数组中添加奇数/偶数循环

时间:2009-09-10 03:24:52

标签: php

这是我的代码:http://www.pcgage.net/code.zip(抱歉,粘贴代码导致它真的搞砸了,即使使用代码容器)。

滚动到第160行(至174) - 这是有问题的循环。我想这样做,这是偶数部分,然后是一些代码,使得奇怪的部分,所以循环按此顺序重复。原因是我想交替改变这个循环的内容。

我不是编码员,所以你能做的最好的事情就是发布新代码,我会把它添加到你告诉我的地方,否则我会迷路:)

希望这是有道理的,如果不是,你可以查看一个关于这个问题的早期帖子,解释为什么我需要这个(在发现单独的css无法解决我的问题之后):css/php: how to solve this div float problem / odd even loop in array

这是循环:

} 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>' . "\n";
                } 



else {              

6 个答案:

答案 0 :(得分:34)

这三种方式是

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

翻转布尔值

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

  $even = !$even;
}

并提到了布尔运算符

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

最快的是布尔运算符。但最强大的是翻转方法,如果你有非常不同的数字(比如运行身份证号码,而有些人遗漏了)。

答案 1 :(得分:8)

我没有查看代码,但是如果它使用变量来计算循环数,你可以这样做:

 for($i=0;$i<$blah;$i++)
   if($i&1){
     // ODD
   }else{
     // EVEN
   }

EDIT(1): 我查看了你遇到的部分,现在我还有另外一个问题,我不确定你是怎么判断什么是奇怪的,所以我提出了两个答案:

1:奇数循环itteration:

   /* Populate the post list array */
// Add here:
   $oddLoop = false;
   foreach ($findposts as $findpost):
//.....
if($oddLoop=!$oddLoop){
  // code for odd loop numbers
}else{
  // code for even loop numbers
}

2:奇数身份证号码:

 } elseif ( ( $findpost->ID ) != $id ) {
    if($findpost->ID & 1){
       // ODD
    }else{
       //EVEN
    }

答案 2 :(得分:5)

在循环中使用条件:

$class = 'odd';  
for(.........) # no problem what kind of loop you are using(for,foreach,while,do)
{
   $class = ($class == 'even' ? 'odd' : 'even');
   #some code 
}

答案 3 :(得分:2)

如果您删除的文章可能会遇到麻烦 - 您的代码会假定ID运行(奇数,偶数,奇数,偶数)等。

更好的想法是创建一个单独的迭代器对象,以便在每一步为您提供必要的值。这是我使用的:

class LoopingPropertyIterator implements Iterator
{
    private $startat = 0, $position = 0;
    private $propertylist = array(
        'boolean' => array(false, true),
        'day' => array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'),
        'dow' => array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')
    );

    public function __construct($args, $startat = 0)
    {
        $this->startat = (int)$startat;
        $this->position = $this->startat;

        foreach ($args as $name => $arr)
            $this->__set($name, $arr);
    }

    public function __get($name)
    {
        if (!array_key_exists($name, $this->propertylist))
            throw new Exception(__METHOD__ . " unknown property $name");

        $t =& $this->propertylist[$name];

        if (is_array($t))
            return $t[$this->position % count($t)];
        else
            return $t;
    }

    public function __set($name, $arr)
    {
        $this->propertylist[$name] = $arr;
    }

    public function current()
    {
        return $this->position;
    }

    public function key()
    {
        return $this->position;
    }

    public function next()
    {
        ++$this->position;
    }

    public function rewind()
    {
        $this->position = $this->startat;
    }

    public function valid()
    {
        return true;
    }
}

然后您的输出简化为

$iter = new LoopingPropertyIterator( array(
    'outerclass' => array('serial-contain-right','serial-contain-left'),
    'innerclass' => array('text-align2','text-align')
));

...

elseif ( $findpost->ID != $id ) {
    $link = get_permalink($firstpost->ID);
    $title = $findpost->post_title;
    $datetime = mysql2date('M jS, Y', $findpost->post_date).' at '.mysql2date('g:ia', $findpost->post_date);

    $serp_list_li[]=
<<<TEXT
    <div class="{$iter.outerclass}">
        <div class="title">
            <h5><a href="{$link}" title="{$title}">{$title}</a></h5>
        </div>
        <div class="{$iter->innerclass}">{$findpost->excerpt}</div>
        <div class="date">{$date}</div>
        <div class="comments">
            <a href="{$link}#comments"> title="{$title}">
                <b>{$findpost->comment_count} Comments</b>
            </a>
        </div>
    </div>
TEXT;

    $iter->next();
}

答案 4 :(得分:0)

您确定$ findpost-&gt; ID包含序列号吗?

你可以用这样的短三元语句替换if / else:

$side = empty($side) || $side == 'right' ? 'left' : 'right';
$serp_list_li[] = '<div class="serial-contain-' . $side . '">' // ...the rest

这将首先添加“左”侧。

答案 5 :(得分:0)

获取EvenArray和OddArray

NSArray *numberArray = [NSArray arrayWithObjects:@1,@2,@3,@4,@6,@8,@10, nil];
for (id object in numberArray)
    {
        if ([object integerValue] % 2 == 0) 
        {
            [evenArray addObject:object];
        } 
        else 
        {
            [oddArray addObject:object];
        }
    }
相关问题