SPL 函数
在线手册:中文 英文
PHP手册

iterator_to_array

(PHP 5 >= 5.1.0)

iterator_to_array将迭代器中的元素拷贝到数组

说明

array iterator_to_array ( Traversable $iterator [, bool $use_keys ] )

将迭代器中的元素拷贝到数组。

参数

iterator

要未拷贝的迭代器。

use_keys

返回值

拷贝后的数组。

更新日志

版本 说明
5.2.1 The use_keys parameter was added.

范例

Example #1 iterator_to_array() example

<?php
$iterator 
= new ArrayIterator(array('recipe'=>'pancakes''egg''milk''flour'));
var_dump(iterator_to_array($iteratortrue));
var_dump(iterator_to_array($iteratorfalse));
?>

以上例程会输出:

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"
}


SPL 函数
在线手册:中文 英文
PHP手册
PHP手册 - N: 将迭代器中的元素拷贝到数组

用户评论:

jerome at yazo dot net (10-Dec-2008 06:42)

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"
)

chad 0x40 herballure 0x2e com (27-Mar-2008 02:23)

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.