php显式迭代数组没有for或foreach

时间:2014-01-28 21:47:27

标签: php arrays iteration

我正在尝试使用next()current()和rewind()迭代一个数组: 有没有一种简单的方法可以知道当前指针何时到达?

我刚刚看到当我在末尾next()和current()返回FALSE时,但当数组单元格包含FALSE布尔值时,这也会附加。

编辑: 当然很抱歉没有指定它是一个数值数组。 我使用它,我正在尝试像

这样的wordpress
while ( have_post() )
      do_post()

但原点可以是数组或PDOStatement,如下所示:

class Document implements ContentGetter{
   private $array_or_rs;
   private $currentval;

   public function have_content() { //part of interface
      if( is_a($this->$array_or_rs, 'PDOStatement') ) {
          $result = PDOStatement-fetch();
          _do_things_
      } else {
          $result = next($this->$array_or_rs);
      }
      $this->$currentval = $result;
      return $result === FALSE;
   }

   public function get_content() { //part of interface
      return $this->$currentval;
   }
}

2 个答案:

答案 0 :(得分:3)

我可以在不使用PHP中的foreach循环的情况下迭代数组吗?

你走了:

$array = array(NULL, FALSE, 0);
while(list($key, $value) = each($array)) {
    var_dump($value);
}

输出:

NULL
bool(false)
int(0)
无法使用

next()current(),因为无法确定FALSE返回值是指FALSE元素还是数组末尾。 (正如你所观察到的那样)。但是,您可以使用函数each(),因为它将返回一个包含当前键和值的数组,或者在数组末尾返回FALSE。执行完毕后,当前指针将被设置为下一个元素。

我必须承认,因为>我没有使用过它。 10年。 :)但它是一个基本的PHP函数,它仍然有效。

如何实施类似WordPres的ContentGetter界面?

我会使用PHP的Iterator概念。您可以将数组包含在ArrayIterator中,也可以将PDOStatement包装到PDOStatementIterator中。虽然第一个是PHP的内置类,但后者必须编写。或者,您可以使用this one(看起来不错,但包含的功能多于此任务所需的功能)

基于此,Document类应该如下所示:

class Document implements ContentGetter {

    /**
     * @var Iterator
     */
    protected $iterator;

    /**
     * @param array|PDOStatement $stmtOrArray
     */
    public function __construct($stmtOrArray) {
        if(is_a($stmtOrArray, 'PDOStatement')) {
            $this->iterator = new PDOStatementIterator($stmtOrArray);
        } else if(is_array($stmtOrArray)) {
            $this->iterator = new ArrayIterator($stmtOrArray);
        } else {
            throw new Exception('Expected array or PDOStatement');
        }
    }

    /**
     * Wrapper for Iterator::valid()
     */
    public function have_content() {
        return $this->iterator->valid();
    }

    /**
     * Wrapper for Iterator::current() + Iterator::next()
     */
    public function get_content() {
        $item = $this->iterator->current();
        $this->iterator->next();
        return $item;
    }
}

<强>试验:

// Feed Document with a PDOStatement
$pdo = new PDO('mysql:host=localhost', 'user', 'password');
$result = $pdo->query('SELECT 1 UNION SELECT 2'); // stupid query ...

$doc = new Document($result);
while($doc->have_content()) {
    var_dump($doc->get_content());
}

// Feed Document with an array
$doc = new Document(array(1, 2, 3));
while($doc->have_content()) {
    var_dump($doc->get_content());
}

答案 1 :(得分:1)

你可以将key()与sizeof($ my_array)进行比较