29

Collection同じタイプのオブジェクトを格納する というクラスがあります。Collection配列インターフェイスを実装します: IteratorArrayAccessSeekableIterator、およびCountable

Collectionオブジェクトを配列引数としてarray_map関数に渡したいと思います。しかし、これはエラーで失敗します

PHP 警告: array_map(): 引数 #2 は配列でなければなりません

Collectionオブジェクトが配列として見えるように、他の/より多くのインターフェースを実装することでこれを達成できますか?

4

5 に答える 5

9

array_map名前が示すように、配列が必要です。やっぱり呼ばiterator_mapれない。;)

潜在的に大きな一時配列を生成する を除けば、iterator_to_array()反復可能なオブジェクトを で動作させるトリックはありませんarray_map

Functional PHPライブラリには、反復可能なコレクションで機能する実装mapがあります。

于 2013-04-29T08:31:40.593 に答える
3

私は次の解決策を思いつきました:

//lets say you have this iterator
$iterator = new ArrayIterator(array(1, 2, 3));

//and want to append the callback output to the following variable
$out = [];

//use iterator to apply the callback to every element of the iterator
iterator_apply(
    $iterator,
    function($iterator, &$out) {
        $current = $iterator->current();
        $out[] = $current*2;
        return true;
    },
    array($iterator, &$out) //arguments for the callback
);

print_r($out);

このようにして、次のようなアプローチのように 2 回繰り返すことなく配列を生成できます。

$iterator = new ArrayIterator(array(1,2,3));
$array = iterator_to_array($iterator); //first iteration
$output = array_map(function() {}, $array); //second iteration

幸運を!

于 2013-12-23T16:08:25.700 に答える