iterator_apply 为迭代器中每个元素调用一个用户自定义函数

发表日期:2021-07-01 08:56:25 | 来源: | | 浏览(705) 分类:SPL 函数

iterator_apply

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

iterator_apply为迭代器中每个元素调用一个用户自定义函数

说明

iterator_apply(Traversable $iterator, callable $function, array $args = ?): int

循环迭代每个元素时调用某一回调函数。

参数

iterator

需要循环迭代的类对象。

function

迭代到每个元素时的调用的回调函数。

注意: 为了遍历 iterator 这个函数必须返回 true

args

传递到回调函数的参数。

返回值

返回已迭代的元素个数。

范例

示例 #1 iterator_apply() example

<?php 
function print_caps(Iterator $iterator) {
    echo strtoupper($iterator->current()) . "\n";
    return TRUE;
}
$it = new ArrayIterator(array("Apples", "Bananas", "Cherries"));
iterator_apply($it, "print_caps", array($it));
?>

以上例程会输出:

APPLES
BANANAS
CHERRIES

参见

  • array_walk() - 使用用户自定义函数对数组中的每个元素做回调处理

集速网 copyRight © 2015-2022 宁ICP备15000399号-1 宁公网安备 64010402001209号
与其临渊羡鱼,不如退而结网
欢迎转载、分享、引用、推荐、收藏。