【问题标题】:Foreach Counter as Array - PHPForeach 计数器作为数组 - PHP
【发布时间】:2014-08-03 19:09:01
【问题描述】:

我的 foreach 语句中有 20 项。 我已经使用 $index = 0 添加了计数器; $索引++

$index = 0;
foreach( $partialStructure as $map ) {

 // i am getting specific number of $tmp for specific subject ( member )
 $tmp = $this->getFieldValueString($field, $value, $subject, $map, $partialStructure);

 $array = array(
      $index => $index,
 );

if(count($array) < 20) {
   // redirect
} else {
  // do nothing
}

$index++;
}

在我的情况下,如果没有 20 个项目,我想将成员重定向到另一个页面。 但是当我检查 ['20'] 并进行其他设置时,其他 1 到 19 仍然存在,并且如果成员有 ['20'] 存在,重定向也会进行。

如果会员有 20 个不重定向的项目,并且如果要重定向的项目少于 20 个,我该如何实现?

谢谢!

【问题讨论】:

  • 不清楚您在这里要做什么。看起来您的整个代码可以简化为 $index = count($partialStructure); $array = array($index =&gt; $index);
  • 您没有显示任何决定何时做什么的代码。添加您现在拥有的代码以做出该决定,问题可能对我们所有人都变得更加清楚
  • 或者您可以直接检查$partialStructure 变量,例如count($partialStructure) &lt; 20
  • 问题越来越复杂了。在我的 foreach 中,我有另一条评论调用 $tmp = $this->getFieldValueString($field, $value, $subject, $map, $partialStructure);这当我计数($tmp)时显示 1,但我的会员有 20 件物品。现在,我不知道,但是索引为数组,我可以算出 $tmp 有 20 个项目。问题是 foreach 从 1 到 19,如果成员有 20 或更少,所有都被重定向,而不是只有一个少于 20 ...
  • 我对我的代码做了一些小改进,以了解我在做什么。

标签: php foreach counter break


【解决方案1】:

您可以只检查数组的长度,而不是通过遍历它来计算长度。

if(count($array)) < 20) {
  //redirect
}else{
  //do whatever you need to do
}

count()

【讨论】:

    【解决方案2】:

    尝试使用 php 函数 count() 来获取数组中元素的数量;) http://fr2.php.net/manual/en/function.count.php

    【讨论】:

      【解决方案3】:

      我这样修复我的代码:

      $counter = 0;
      $tmp= array();
      foreach( $partialStructure as $map ) {
      
       // i am getting specific number of $tmp for specific subject ( member )
       $tmp[] = $this->getFieldValueString($field, $value, $subject, $map, $partialStructure);
      
      if($tmp['20'])
      $counter++;
      
      
      }
      // out of foreach element, i setup this
      if($counter == 0) {
         header("Location: /members/edit/profile?redirect=1");     
      }
      

      $counter 会给你 1,如果 tmp['20'] 在那里,否则,你可以做重定向...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-13
        • 2016-09-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多