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

时间:2012-04-02 08:27:18

标签: php foreach iterator arrayaccess

有没有办法迭代实现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

感谢您提供任何帮助和提示。

2 个答案:

答案 0 :(得分:3)

我用它来实现迭代器。也许你可以适应你的代码;)

class ModelList implements Iterator{
public $list;
private $index = 0;
public $nb;
public $nbTotal;

/**
 * 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;}
/**
 * 
 * Constructor
 */
public function __construct() {
    $this->list = array();
    $this->nb = 0;
    $this->nbTotal = 0;
    return $this;
}
}

答案 1 :(得分:2)

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

这是我的方法,但是,这个函数看起来不确定:

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

增加“一个”不太可能给你“两个”。尝试this question的答案中的代码以获取下一个数组键:

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