【问题标题】:PHP testing for a next item下一项的 PHP 测试
【发布时间】:2015-04-08 20:51:19
【问题描述】:

我不知道如何使用要测试的密钥来测试我的数组中是否有下一项。我认为这在代码中得到了更好的解释。我知道有更简单的方法,我只是个菜鸟!

基本上我想知道数组中是否还有其他项目,如果有,则获取 ->comp_id 值。

for($i=0; $i<count($allcomps); $i++)
    {
        if($allcomps[$i]->comp_id  == $curCompID)
        {
            $currentIndex = $i;
            if($allcomps[$i+1]->comp_id == null )
            {
                echo "there isn't a next";
            }
            //echo $allcomps[$currentIndex+1]->comp_id;
        }
    }

【问题讨论】:

  • if (isset($allcomps[$i + 1])) { echo $allcomps[$i + 1]-&gt;comp_id; }
  • @scrowler,我认为 OP 会想要 (!isset($allcomps[$i + 1]))
  • @Devon 为什么? 我想知道数组中是否还有其他项,如果有则获取comp_id
  • 好吧,实际上这有点令人困惑。代码说一件事,但问题说,如果是这样,请获取 ->comp_id 值。所以我想 OP 将不得不决定一个。

标签: php loops key


【解决方案1】:

您已经在循环遍历所有comps,那么为什么还需要检查下一个呢?

为什么不在循环内检查?

for($i=0; $i<count($allcomps); $i++) {
  if (isset($allcomps[$i]->comp_id) and $allcomps[$i]->comp_id == $curCompID) {
    $currentIndex = $i;
  }
}

我认为 foreach 可能更容易:

foreach($allcomps as $i=>$comp) {
  if (isset($comp->comp_id) and $comp->comp_id == $curCompID) {
    $currentIndex = $i;
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-21
    • 1970-01-01
    • 2018-06-15
    • 1970-01-01
    • 2012-07-29
    • 1970-01-01
    • 2013-03-18
    • 1970-01-01
    相关资源
    最近更新 更多