(PHP 5 >= 5.1.0, PHP 7, PHP 8)
AppendIterator::__construct — 构造 AppendIterator
构造 AppendIterator。
此函数没有参数。
示例 #1 使用 foreach 迭代 AppendIterator
<?php
$pizzas = new ArrayIterator(array('Margarita', 'Siciliana', 'Hawaii'));
$toppings = new ArrayIterator(array('Cheese', 'Anchovies', 'Olives', 'Pineapple', 'Ham'));
$appendIterator = new AppendIterator;
$appendIterator->append($pizzas);
$appendIterator->append($toppings);
foreach ($appendIterator as $key => $item) {
echo $key . ' => ' . $item . PHP_EOL;
}
?>
以上示例将输出
0 => Margarita 1 => Siciliana 2 => Hawaii 0 => Cheese 1 => Anchovies 2 => Olives 3 => Pineapple 4 => Ham
示例 #2 使用 AppendIterator API 迭代 AppendIterator
<?php
$pizzas = new ArrayIterator(array('Margarita', 'Siciliana', 'Hawaii'));
$toppings = new ArrayIterator(array('Cheese', 'Anchovies', 'Olives', 'Pineapple', 'Ham'));
$appendIterator = new AppendIterator;
$appendIterator->append($pizzas);
$appendIterator->append($toppings);
while ($appendIterator->valid()) {
printf(
'%s => %s => %s%s',
$appendIterator->getIteratorIndex(),
$appendIterator->key(),
$appendIterator->current(),
PHP_EOL
);
$appendIterator->next();
}
?>
以上示例将输出
0 => 0 => Margarita 0 => 1 => Siciliana 0 => 2 => Hawaii 1 => 0 => Cheese 1 => 1 => Anchovies 1 => 2 => Olives 1 => 3 => Pineapple 1 => 4 => Ham
当使用 iterator_to_array() 将 AppendIterator 的值复制到数组中时,您必须将可选的 use_key
参数设置为 false
。当 use_key
不是 false
时,在内部迭代器中重复出现的任何键都将在返回的数组中被覆盖。没有办法保留原始键。