【问题标题】:PHP array index mishapPHP数组索引事故
【发布时间】:2012-06-15 03:25:23
【问题描述】:

抱歉这个时髦的标题,我很难想出一个。首先,我设法真正解决了我的问题(在拆开我的代码之后),但我不知道为什么我的解决方案有效,我试图将其视为一种学习体验。

我有一个从数据库收集信息的类。此类跟踪索引值,以便调用函数一次获取一个结果。所以我的课程代码最初包含...

protected $index = NULL;
protected $array = array(stuff);

public function next_item()
{
    if($this->index == NULL)
    {//first time called
        $this->index = 0;
    }
    else
    {
        $this->index++;
    }

    if($this->index < sizeof($this->array))
    {
          return TRUE;
     }
      return FALSE;
 }

 public function get_result()
 {
      return $this->array[$this->index];
  }

调用函数类似于

 while($myclass->next_item()){
        echo $myclass->get_result();
 }

当然,这比这要复杂得多,但这是问题代码(你明白了)。这段代码在我的项目中引发了一个无限循环(或出现一个)。我通过将 $index 初始化为 -1 并删除对 null 的条件检查来解决我的问题。所以现在...

protected $index = -1;

public function next_item()
{
    $this->index++;

    if($this->index < sizeof($this->array))
    {
          return TRUE;
    }
    return FALSE;
}

我的问题是,为什么这样做有效?我检查过,当它为 NULL 时,数组中从未引用过该索引。它总是在调用 NULL 的条件检查并分配给 0 之后发生。

非常感谢您提前抽出宝贵时间。只是想把它变成一种学习体验,如果我能理解它为什么起作用,而不仅仅是它起作用,那就更好了。

很抱歉,如果这个问题在其他地方得到了回答,我不知道如何标记我的问题(如您所见),更不用说成功找到以前的答案了。

干杯, -大卫

【问题讨论】:

  • 您实际上可以使用if (++$this-&gt;index &lt; sizeof($this-&gt;array)) 来保存一行,它会为您增加它。

标签: php arrays null indexing


【解决方案1】:

您的问题是由 PHP 中的 0 == NULL 引起的。因此,当您将索引设置为0 时,您会在每次调用next_item 时一遍又一遍地将其设置为0this-&gt;index == NULL 将始终为真。

将您的测试更改为this-&gt;index === NULL 也可以解决您的问题。请参阅 this question,它涵盖了 PHP 中 ===== 之间的区别。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-25
  • 1970-01-01
  • 1970-01-01
  • 2011-11-24
  • 1970-01-01
  • 1970-01-01
  • 2014-11-25
相关资源
最近更新 更多