有数组接口的集合上的array_map? [英] array_map on collection with array interfaces?

查看:178
本文介绍了有数组接口的集合上的array_map?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 Collection 的类,它存储相同类型的对象。
集合实现数组接口: Iterator ArrayAccess SeekableIterator 可数

I have a class called Collection which stores objects of same type. Collection implements array interfaces: Iterator, ArrayAccess, SeekableIterator, and Countable.

我' d想将 Collection 对象作为数组参数传递给 array_map 功能。但是失败并出现错误

I'd like to pass a Collection object as the array argument to the array_map function. But this fails with the error


PHP警告:array_map():参数#2应该是一个数组

PHP Warning: array_map(): Argument #2 should be an array

我是否可以通过实现其他/更多接口来实现这一点,以便 Collection 对象被视为数组?

Can I achieve this by implementing other/more interfaces, so that Collection objects are seen as arrays?

推荐答案

array_map()函数不支持 Traversable 作为其数组参数,因此您必须执行转换步骤:

The array_map() function doesn't support a Traversable as its array argument, so you would have to perform a conversion step:

array_map($fn, iterator_to_array($myCollection));

除了对集合进行两次迭代之外,它还会生成一个之后不会使用的数组。

Besides iterating over the collection twice, it also yield an array that will not be used afterwards.

另一种方法是编写自己的地图功能:

Another way is to write your own map function:

function map(callable $fn)
{
    $result = array();

    foreach ($this as $item) {
        $result[] = $fn($item);
    }

    return $result;
}

更新

根据您的用例判断,您似乎对地图操作的结果不感兴趣;因此,使用 iterator_apply() 更有意义。

Judging by your use-case it seems that you're not even interested in the result of the map operation; therefore it makes more sense to use iterator_apply().

iterator_apply($myCollection, function($obj) {
    $obj->method1();
    $obj->method2();

    return true;
});

这篇关于有数组接口的集合上的array_map?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆