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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1403213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:26:19  来源:igfitidea点击:

php: how to add odd/even loop in array

php

提问by Jim

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).

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

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.

滚动到行:160(到 174) - 这是有问题的循环。我想使它成为偶数部分,然后是一些代码来制作奇数部分,因此循环按此顺序重复。原因是我想交替更改此循环的内容。

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

希望这是有道理的,如果没有,您可以查看有关此问题的早期帖子,该帖子解释了为什么我需要这个(在发现仅靠 css 无法解决我的问题之后):css/php:如何解决此 div 浮动问题/奇偶循环在数组中

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



else {              

回答by raspi

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).

最快的是布尔运算符。但是,如果您有非常不同的数字(例如通过 ID 编号运行并且某些编号丢失),则最可靠的方法是翻转方法。

回答by scragar

I haven't looked over the code, but if it's using a variable to count the loop number you can do:

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

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

EDIT(1): I looked at the section you are running into, and now I have another problem, I'm unsure how you are judging what should be odd or not, so I propose two answers:

编辑(1):我查看了您遇到的部分,现在我有另一个问题,我不确定您如何判断什么应该是奇怪的,所以我提出两个答案:

1: odd loop itteration:

1:奇数循环迭代:

   /* 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: Odd ID number:

2:奇数身号码:

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

回答by M Rostami

For loops increment by 1:

For 循环递增 1:

$state = 'odd';  
for (...)
{
   $state = ($state == 'even' ? 'odd' : 'even');
   echo $state . PHP_EOL;
}

Output:

输出:

even
odd
even
odd
...

回答by Hugh Bothwell

If you ever delete an article you could be in trouble - your code assumes that ID runs (odd,even,odd,even) etc.

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

A better idea would be to create a separate iterator object to feed you the necessary values at each step. Here's what I use:

一个更好的主意是创建一个单独的迭代器对象来为您提供每一步所需的值。这是我使用的:

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;
    }
}

then your output simplifies to

那么你的输出简化为

$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();
}

回答by Anusha Patil

Get EvenArray and OddArray

获取 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];
        }
    }

回答by rojoca

Are you sure $findpost->ID contains sequential numbers?

您确定 $findpost->ID 包含序列号吗?

You could replace the if/else with s short ternary statement like this:

您可以将 if/else 替换为如下所示的短三元语句:

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

This would add a 'left' side first.

这将首先添加一个“左侧”。