©
このドキュメントでは、 php中国語ネットマニュアル リリース
(PHP 5 >= 5.1.0)
iterator_to_array — 将迭代器中的元素拷贝到数组
$iterator
[, bool $use_keys
= true
] )将迭代器中的元素拷贝到数组。
iterator
被拷贝的迭代器。
use_keys
是否使用迭代器元素键作为索引。
一个数组,包含迭代器中的元素。
版本 | 说明 |
---|---|
5.2.1 |
添加了 use_keys 参数。
|
Example #1 iterator_to_array() example
<?php
$iterator = new ArrayIterator (array( 'recipe' => 'pancakes' , 'egg' , 'milk' , 'flour' ));
var_dump ( iterator_to_array ( $iterator , true ));
var_dump ( iterator_to_array ( $iterator , false ));
?>
以上例程会输出:
array(4) { ["recipe"]=> string(8) "pancakes" [0]=> string(3) "egg" [1]=> string(4) "milk" [2]=> string(5) "flour" } array(4) { [0]=> string(8) "pancakes" [1]=> string(3) "egg" [2]=> string(4) "milk" [3]=> string(5) "flour" }
[#1] Harry Willis [2015-06-07 21:21:28]
When using iterator_to_array() on an SplObjectStorage object, it's advisable to set $use_keys to false.
The resulting array is identical, since the iterator keys produced by SplObjectStorage::key() are always integers from 0 to (COUNT-1). Passing $use_keys=false cuts out the unnecessary calls to SplObjectStorage::key(), giving a slight performance advantage.
[#2] joksnet at gmail dot com [2014-10-26 20:36:33]
To generate an deep array from nested iterators:
<?php
function iterator_to_array_deep(\Traversable $iterator, $use_keys = true) {
$array = array();
foreach ($iterator as $key => $value) {
if ($value instanceof \Iterator) {
$value = iterator_to_array_deep($value, $use_keys);
}
if ($use_keys) {
$array[$key] = $value;
} else {
$array[] = $value;
}
}
return $array;
}
?>
I use it to test an iterator: https://gist.github.com/jm42/cb328106f393eeb28751
[#3] jerome at yazo dot net [2008-12-09 22:42:37]
Using the boolean param :
<?php
$first = new ArrayIterator( array('k1' => 'a' , 'k2' => 'b', 'k3' => 'c', 'k4' => 'd') );
$second = new ArrayIterator( array( 'k1' => 'X', 'k2' => 'Y', 'Z' ) );
$combinedIterator= new AppendIterator();
$combinedIterator->append( $first );
$combinedIterator->append( $second );
var_dump( iterator_to_array($combinedIterator, false) );
?>
will output :
array(7) (
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
[3]=>
string(1) "d"
[4]=>
string(1) "X"
[5]=>
string(1) "Y"
[6]=>
string(1) "Z"
)
<?php
var_dump( iterator_to_array($combinedIterator, true) );
?>
will output (since keys would merge) :
array(5) (
["k1"]=>
string(1) "X"
["k2"]=>
string(1) "Y"
["k3"]=>
string(1) "c"
["k4"]=>
string(1) "d"
[0]=>
string(1) "Z"
)
[#4] chad 0x40 herballure 0x2e com [2008-03-27 06:23:42]
The use_keys parameter was added in one of the 5.2.x releases; it defaults to TRUE. This matches the behavior in PHP 5.1.6, which lacks this parameter.