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
La clase ArrayIterator
(PHP 5)
Introducción
Este iterador permite eliminar y modificar valores y claves cuando se itera sobre arrays y objetos.
Cuando se quiere iterar sobre el mismo array varias veces, se necesita instanciar ArrayObject y dejar que cree instancias ArrayIterator que refieren a la misma usando foreach o llamando su método getIterator() de forma manual.
Sinopsis de la Clase
ArrayIterator
implements
Iterator
,
Traversable
,
ArrayAccess
,
SeekableIterator
,
Countable
,
Serializable
{
/* Métodos */
}Tabla de contenidos
- ArrayIterator::append — Añade un elemento
- ArrayIterator::asort — Ordena array por sus valores
- ArrayIterator::__construct — Construye un ArrayIterator
- ArrayIterator::count — Cuenta elementos
- ArrayIterator::current — Devuelve la entrada actual del array
- ArrayIterator::getArrayCopy — Obtener copia de un array
- ArrayIterator::getFlags — Obtener opciones
- ArrayIterator::key — Devuelve la clave actual del array
- ArrayIterator::ksort — Ordena un array por sus claves
- ArrayIterator::natcasesort — Ordena un array de forma natural, sensible a mayúsculas
- ArrayIterator::natsort — Ordena un array de forma natural
- ArrayIterator::next — Desplaza a la siguiente entrada
- ArrayIterator::offsetExists — Compruebar si el índice existe
- ArrayIterator::offsetGet — Obtener el valor de un índice
- ArrayIterator::offsetSet — Establece el valor para un índice
- ArrayIterator::offsetUnset — Destruye el valor de un índice
- ArrayIterator::rewind — Rebobinar array al inicio
- ArrayIterator::seek — Buscar la posición
- ArrayIterator::serialize — Serializar
- ArrayIterator::setFlags — Definir opciones de comportamiento
- ArrayIterator::uasort — Ordenado definido por el usuario
- ArrayIterator::uksort — Ordenado definido por el usuario
- ArrayIterator::unserialize — Deserializar
- ArrayIterator::valid — Comprueba si un array contiene más entradas
Sean Burlington ¶
3 years ago
Relakuyae ¶
1 year ago
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"));
?>
Venelin Vulkov ¶
4 years ago
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.
foobuilder at gmail dot com ¶
2 years ago
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.
