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"));
?>
La classe ArrayIterator
(PHP 5)
Introduction
Cet itérateur permet de réinitialiser et de modifier les valeurs et les clés lors de l'itération de tableaux et d'objets.
Lorsque vous voulez passer en revue le même tableau plusieurs fois, vous devez instancier ArrayObject et le laisser créer les objets ArrayIterator qui s'y réfèrent, soit en utilisant l'instruction foreach, soit en appelant la méthode getIterator()() manuellement.
Synopsis de la classe
ArrayIterator
implements
Iterator
,
Traversable
,
ArrayAccess
,
SeekableIterator
,
Countable
,
Serializable
{
/* Méthodes */
}Sommaire
- ArrayIterator::append — Ajoute un élément
- ArrayIterator::asort — Trie un tableau par les valeurs
- ArrayIterator::__construct — Construit un ArrayIterator
- ArrayIterator::count — Compte les éléments
- ArrayIterator::current — Retourne l'entrée courante du tableau
- ArrayIterator::getArrayCopy — Récupère la copie d'un tableau
- ArrayIterator::getFlags — Récupère un comportement
- ArrayIterator::key — Retourne la clé courante du tableau
- ArrayIterator::ksort — Trie un tableau par les clés
- ArrayIterator::natcasesort — Trie naturellement un tableau, en ne tenant pas compte de la casse
- ArrayIterator::natsort — Trie naturellement un tableau
- ArrayIterator::next — Se déplace vers la prochaine entrée
- ArrayIterator::offsetExists — Vérifie si une position existe
- ArrayIterator::offsetGet — Récupère la valeur pour une position
- ArrayIterator::offsetSet — Définit la valeur d'une position
- ArrayIterator::offsetUnset — Efface la valeur d'une position
- ArrayIterator::rewind — Revient à la position initiale
- ArrayIterator::seek — Avance à une position donnée
- ArrayIterator::serialize — Linéarisation
- ArrayIterator::setFlags — Définit des comportements
- ArrayIterator::uasort — Tri défini par l'utilisateur
- ArrayIterator::uksort — Trie défini par l'utilisateur
- ArrayIterator::unserialize — Délinéarisation
- ArrayIterator::valid — Vérifie si un tableau contient d'autres entrées
Relakuyae
19-Oct-2011 05:23
foobuilder at gmail dot com
09-Dec-2010 11:01
Unsetting all keys of an ArrayItem within foreach will always leave the second key:
<?php
$items = new ArrayObject(range(0, 9));
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.
liranuna at liranuna dot com
02-Dec-2009 06:44
If you want to make your ArrayIterator support foreach loops with PHP's & operator, such as
<?php
foreach($list as &$item) {
....
}
?>
You will need to pass the array to ArrayIterator by reference:
<?php
new ArrayIterator(&$array);
?>
Sean Burlington
26-May-2009 05:15
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
Venelin Vulkov
11-Nov-2008 03:44
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";
/* Outputs something like */
Iterating over: 4 values
apple=yummy
orange=ah ya, nice
grape=wow, I love it!
plum=nah, not me
?>
Regards.
