文字

The ArrayIterator class

(PHP 5)

简介

这个迭代器允许在遍历数组和对象时删除和更新值与键

当你想多次遍历相同数组时你需要实例化ArrayObject,然后让这个实例创建一个ArrayIteratror实例 当你想遍历相同数组时多次你需要实例ArrayObject并且让这个实例创建一个ArrayIteratror实例,然后使用foreach或者 手动调用getIterator()方法

类摘要

ArrayIterator implements ArrayAccess , SeekableIterator , Countable , Serializable {
public void append ( mixed $value )
public void asort ( void )
public __construct ([ mixed $array = array() [, int $flags = 0 ]] )
public int count ( void )
public mixed current ( void )
public array getArrayCopy ( void )
public void getFlags ( void )
public mixed key ( void )
public void ksort ( void )
public void natcasesort ( void )
public void natsort ( void )
public void next ( void )
public void offsetExists ( string $index )
public mixed offsetGet ( string $index )
public void offsetSet ( string $index , string $newval )
public void offsetUnset ( string $index )
public void rewind ( void )
public void seek ( int $position )
public string serialize ( void )
public void setFlags ( string $flags )
public void uasort ( string $cmp_function )
public void uksort ( string $cmp_function )
public string unserialize ( string $serialized )
public bool valid ( void )
}

Table of Contents

  • ArrayIterator::append — Append an element
  • ArrayIterator::asort — Sort array by values
  • ArrayIterator::__construct — Construct an ArrayIterator
  • ArrayIterator::count — Count elements
  • ArrayIterator::current — Return current array entry
  • ArrayIterator::getArrayCopy — Get array copy
  • ArrayIterator::getFlags — Get flags
  • ArrayIterator::key — Return current array key
  • ArrayIterator::ksort — Sort array by keys
  • ArrayIterator::natcasesort — Sort an array naturally, case insensitive
  • ArrayIterator::natsort — Sort an array naturally
  • ArrayIterator::next — Move to next entry
  • ArrayIterator::offsetExists — Check if offset exists
  • ArrayIterator::offsetGet — Get value for an offset
  • ArrayIterator::offsetSet — Set value for an offset
  • ArrayIterator::offsetUnset — Unset value for an offset
  • ArrayIterator::rewind — Rewind array back to the start
  • ArrayIterator::seek — Seek to position
  • ArrayIterator::serialize — Serialize
  • ArrayIterator::setFlags — Set behaviour flags
  • ArrayIterator::uasort — User defined sort
  • ArrayIterator::uksort — User defined sort
  • ArrayIterator::unserialize — Unserialize
  • ArrayIterator::valid — Check whether array contains more entries

用户评论:

[#1] daniel dot rutkoski at gmail dot com [2015-09-25 02:28:30]

<?php
class PrintArray
{
    private $code = null;

    function __construct ($val)
    {
        $this->code = $val;
        $this->_print();
    }
    
    private function arrayIterator($val, $grau)
    {
        $grau++;
        $arr = new \ArrayIterator($val);
        while ($arr->valid())
        {
            if(is_array($arr->current()))
            {
                $this->arrayIterator($arr->current(), $grau);
            }
            else
            {
                $this->code .= str_repeat(" ", (4 * $grau)) . $arr->key() . " : " . $arr->current() . PHP_EOL;
            }
            $arr->next();
        }
    }
    
    private function _print() 
    {
        if (is_array($this->code))
        {
            $arr = new \ArrayIterator($this->code);
            $this->code = 'array(' . PHP_EOL;
            while ($arr->valid())
            {
                if(is_array($arr->current()))
                {
                    $this->arrayIterator($arr->current(), 0);
                }
                else
                {
                    $this->code .= $arr->key() . " : " . $arr->current() . "\n";
                }
                $arr->next();
            }
            $this->code .= ')';
        }
        return $this;
    }
    
    public function getVal ()
    {
        return $this->code;
    }
}

$arr = array(
    array(
        'ok' => 1, array(9,7,5,9,'a','b'=>array(1,2)),
        'error' => 2, array('h','u','o')
    )
    , 'array'
);
$pArray = new PrintArray($arr);
var_dump($pArray->getVal());

[#2] Relakuyae [2011-10-19 17:23:33]

Need a callback on an iterated value, but don't have PHP 5.4+?  This makes is stupid easy:

<?php
class ArrayCallbackIterator extends ArrayIterator {
  private 
$callback;
  public function 
__construct($value$callback) {
    
parent::__construct($value);
    
$this->callback $callback;
  }

  public function 
current() {
    
$value parent::current();
    return 
call_user_func($this->callback$value);
  }
}
?>


You can use it pretty much exactly as the Array Iterator:

<?php
$iterator1 
= new ArrayCallbackIterator($valueList"callback_function");
$iterator2 = new ArrayCallbackIterator($valueList, array($object"callback_class_method"));
?>

[#3] foobuilder at gmail dot com [2010-12-09 11:01:25]

Unsetting all keys of an ArrayItem within foreach will always leave the second key: 

<?php
$items 
= new ArrayObject(range(09)); 

while (list(
$k$v) = each($items)) {
    unset(
$items[$k]); 
}

print_r($items); 

//  ArrayIterator Object
//  (
//      [storage:ArrayIterator:private] => Array
//          (
//              [1] => 1
//          )
//  )
?>


I'm not sure if this is a bug as unsetting keys within foreach is usually a bad idea to begin with (use while instead), but it's something to be aware of.

[#4] Sean Burlington [2009-05-26 05:15:47]

and to iterate recursively use the (sparsely documented)  RecursiveArrayIterator

<?php

$fruits 
= array(
                
"apple" => "yummy",
                
"orange" => "ah ya, nice",
                
"grape" => "wow, I love it!",
                 
"plum" => "nah, not me"
                
);

$veg = array("potato" => "chips""carrot" => "soup");
$grocery = array($fruits$veg);
$obj = new ArrayObject$grocery );

$it = new RecursiveIteratorIterator( new RecursiveArrayIterator($grocery));

foreach (
$it as $key=>$val)
echo 
$key.":".$val."\n";

?>


Output
--------
apple:yummy
orange:ah ya, nice
grape:wow, I love it!
plum:nah, not me
potato:chips
carrot:soup

[#5] Venelin Vulkov [2008-11-11 03:44:02]

Another fine Iterator from php . You can use it especially when you have to iterate over objects

<?php
$fruits 
= array(
    
"apple" => "yummy",
    
"orange" => "ah ya, nice",
    
"grape" => "wow, I love it!",
    
"plum" => "nah, not me"
);
$obj = new ArrayObject$fruits );
$it $obj->getIterator();

// How many items are we iterating over?

echo "Iterating over: " $obj->count() . " values\n";

// Iterate over the values in the ArrayObject:
while( $it->valid() )
{
    echo 
$it->key() . "=" $it->current() . "\n";
    
$it->next();
}

// The good thing here is that it can be iterated with foreach loop

foreach ($it as $key=>$val)
echo 
$key.":".$val."\n";



Iterating over4 values
apple
=yummy
orange
=ah yanice
grape
=wowI love it!
plum=nahnot me

?>


Regards.

上一篇: 下一篇: