【问题标题】:php: how to add odd/even loop in arrayphp:如何在数组中添加奇/偶循环
【发布时间】:2009-09-10 03:24:52
【问题描述】:

这是我的代码: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 {              

【问题讨论】:

  • 我不确定你到底在问什么,但由于你对第一篇文章的编辑,我确实找到了你的代码(由于某种原因在我的编辑器中的第 320 行左右,很多额外的新代码中的行)。根据您的要求,我提供了两个修复程序,对此我有点不清楚,但是除非我错过了第三个问题,否则此解决方案应该可以工作。
  • @scragar,你帮助我们走得更远,但似乎有问题,见上文。
  • 你真的应该使用模板引擎!你在搞乱代码和设计

标签: php


【解决方案1】:

三种方式

取模

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

最快的是布尔运算符。但是,如果您有非常不同的号码(例如遍历 ID 号码并且有些号码丢失),最可靠的方法是翻转方法。

【讨论】:

  • 虽然我确信这些都能正常工作,但我不是程序员,所以要修改你的代码以在我的脚本中工作,好吧,我一无所知。不过,谢谢。
【解决方案2】:

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

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

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

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:奇数ID号:

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

【讨论】:

  • 希望我有足够的信心尝试把它放在正确的地方,但我不是。我已经把循环代码放在帖子里了,希望能帮助我告诉我把这个放在哪里,谢谢!
  • 我一定算过里面有一些空行,寻找这个评论行://除了当前帖子之外的所有其他帖子都是这个循环。
  • 我了解第 2 步,只是不了解第 1 步。假设我将替换所有从 /* 填充帖子列表数组 */ 到 // 我们有当前帖子并且要显示链接 - 对于你的新代码,那会是什么?对不起,我不擅长 php :(
  • 对此有任何帮助,我觉得很接近解决方案
  • 选项 2 不起作用,它只执行数组的第一次迭代,所有其他的都不交替
【解决方案3】:

For 循环加 1:

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

输出:

even
odd
even
odd
...

【讨论】:

  • 这是一个非常甜蜜的方法。
  • 超级干净的方法
【解决方案4】:

如果您删除了一篇文章,您可能会遇到麻烦 - 您的代码假定 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();
}

【讨论】:

  • 听起来不错,但对于不编码的人(我)来说,这一切都变得复杂了。除非我能得到某人的 php 文件更新并发回,否则我永远不会让它工作:(
  • 我在pastebin.com/m2606fee0 为您修补了您的文件 - 正如您所看到的,这只是剪切和粘贴到适当位置的问题。希望对您有所帮助。
【解决方案5】:

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

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

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

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

【讨论】:

    【解决方案6】:

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

    【讨论】:

      猜你喜欢
      • 2012-10-10
      • 1970-01-01
      • 2011-12-31
      • 1970-01-01
      • 2012-10-10
      • 2016-10-12
      • 2010-11-26
      • 1970-01-01
      • 2011-04-30
      相关资源
      最近更新 更多