函数所需的每个参数都必须位于传递给 iterator_apply 的第三个参数中的数组中。您也可以使用引用。示例
<?php
function translate_to(string $target_language, Iterator $words, array $dictionaries) {
$language = ucfirst($target_language);
$dictionary = $dictionaries[$target_language] ?? 'not found';
if ($dictionary === 'not found') {
echo "Not found dictionary for {$language}\n";
return;
}
echo "English words translated to {$language}\n";
$not_found = [];
iterator_apply($words, function($words, $dictionary, &$not_found){
$english_word = $words->current();
$translated_word = $dictionary[$english_word] ?? '';
if ($translated_word !== '') {
echo "{$english_word} translates to {$translated_word}\n";
} else {
$not_found[] = $english_word;
}
return true;
}, array($words, $dictionary, &$not_found));
echo "\nNot found words:\n" . implode("\n", $not_found) . "\n";
}
$dictionaries = [
'nahuatl' => [
'one' => 'Ze',
'two' => 'Ome',
'three' => 'Yei',
'four' => 'Nahui',
],
];
$iterator = new \ArrayIterator(array('one', 'two', 'three', 'four', 'gasoil'));
translate_to('nahuatl', $iterator, $dictionaries);
?>
英语单词翻译成纳瓦特尔语
one 翻译成 Ze
two 翻译成 Ome
three 翻译成 Yei
four 翻译成 Nahui
未找到的单词
gasoil