在实现 ArrayAccess 和 Iterator 的对象上使用 foreach

问题描述 投票:0回答:2

有没有一种方法可以迭代实现 ArrayAccess 和 Iterator 接口的对象的键?数组访问很有魅力,但我不能在那些对象上使用 foreach,这对我有很大帮助。是否可以?到目前为止我有这样的代码:

<?php
class IteratorTest implements ArrayAccess, Iterator {
  private $pointer = 0;

  public function offsetExists($index) {
    return isset($this->objects[$index]);
  }

  public function offsetGet($index) {
    return $this->objects[$index];
  }

  public function offsetSet($index, $newValue) {
    $this->objects[$index] = $newValue;
  }

  public function offsetUnset($index) {
    unset($this->objects[$index]);
  }

  public function key() {
    return $this->pointer;
  }

  public function current() {
    return $this->objects[$this -> pointer];
  }

  public function next() {
    $this->pointer++;
  }

  public function rewind() {
    $this->pointer = 0;
  }

  public function seek($position) {
    $this->pointer = $position;
  }

  public function valid() {
    return isset($this->objects[$this -> pointer]);
  }
}

$it = new IteratorTest();

$it['one'] = 1;
$it['two'] = 2;

foreach ($it as $k => $v) {
  echo "$k: $v\n";
}

// expected result:
// one: 1
// two: 2

感谢您的帮助和提示。

php foreach iterator arrayaccess
2个回答
3
投票

我用它来实现

Iterator
。也许您可以将其调整为您的代码;)

class ModelList implements Iterator {
    public  $list;

    private $index = 0;

    public  $nb;

    public  $nbTotal;

    public function __construct() {
        $this->list    = [];
        $this->nb      = 0;
        $this->nbTotal = 0;

        return $this;
    }

    /**
     * list navigation
     */
    public function rewind() {
        $this->index = 0;
    }

    public function current() {
        $k   = array_keys( $this->list );
        $var = $this->list[ $k[ $this->index ] ];

        return $var;
    }

    public function key() {
        $k   = array_keys( $this->list );
        $var = $k[ $this->index ];

        return $var;
    }

    public function next() {
        $k = array_keys( $this->list );
        if ( isset( $k[ ++$this->index ] ) ) {
            $var = $this->list[ $k[ $this->index ] ];

            return $var;
        } else {
            return false;
        }
    }

    public function valid() {
        $k   = array_keys( $this->list );
        $var = isset( $k[ $this->index ] );

        return $var;
    }
}

2
投票
while ($it->valid()) {
    echo $it->key().' '.$it->current();
    $it->next();
}

这将是我的方法,但是,这个函数看起来不太可靠:

 public function next() {
    $this->pointer++;
 }

增加“一”不太可能给你“二”。尝试使用这个问题的答案中的代码来获取下一个数组键:

$keys = array_keys($this->objects);
$position = array_search($this->key(), $keys);
if (isset($keys[$position + 1])) {
    $this->pointer = $keys[$position + 1];
} else {
    $this->pointer = false;
}
© www.soinside.com 2019 - 2024. All rights reserved.