我想出了以下解決方案:
//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);
這樣,你就可以生成一個數組不反覆兩次,你將通過類似的方法來:
$iterator = new ArrayIterator(array(1,2,3));
$array = iterator_to_array($iterator); //first iteration
$output = array_map(function() {}, $array); //second iteration
好運氣!
推出自己的collection_map功能? – Adder 2013-04-29 08:21:05
@Adder Course我可以,但現在我正在尋找解決方案,如果我可以使用我的集合與buildin php funcs :) – f1ames 2013-04-29 08:28:23