array_map并将2个参数传递给映射函数-array_map():参数3应该是一个数组 [英] array_map and pass 2 arguments to the mapped function - array_map(): Argument #3 should be an array

查看:348
本文介绍了array_map并将2个参数传递给映射函数-array_map():参数3应该是一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个抽象类,如下所示:

I have an abstract class that looks like this:

abstract class Transformer {

    /**
     * Transform a collection of items
     *
     * @param array $items
     * @param bool $format
     * @return array
     */
    public function transformCollection(array $items, $format)
    {
        return array_map([$this, 'transform'], $items, $format);
    }

    /**
     * Transform a item
     *
     * @param array $item
     * @param bool $format
     * @return mixed
     */
    public abstract function transform(array $item, $format);

}

然后,我有以下实现它的类:

Then I have the following class that implements it:

class ServiceLogTransformer extends Transformer {

    public function transform(array $service_log, $format = false)
    {
        return [
            'id'    => $service_log['id'],
            'date'  => $service_log['log_date'],
            'time'  => $service_log['log_time'],
            'type'  => ($format ? status_label($service_log['log_type']) : $service_log['log_type']),
            'entry' => $service_log['log_entry']
        ];
    }

}

此代码运行时,出现错误:

When this code runs, I get the error:

在类中调用array_map函数时如何传递2个或更多参数?我检查了PHP文档,看起来这是允许的,但是在我的Larave 4.2项目上不起​​作用.

How do you pass 2 or more arguments when you call array_map function within a class? I checked the PHP Documentation and it looks like this is allowed, but it isn't working on my Larave 4.2 project.

有什么想法吗?

推荐答案

请始终阅读文档:

http://php.net/manual/en/function.array- map.php

array array_map ( callable $callback , array $array1 [, array $... ] )

,但是您将bool $format作为参数传递

and yet you pass bool $format as argument

调用array_map函数时如何传递2个或更多参数 在班上?

"How do you pass 2 or more arguments when you call array_map function within a class?

我将使用use()语法创建匿名函数

I would create anonymous function with use() syntax

public function transformCollection(array $items, $format)
{
    return array_map(function($item) use ($format) {
        return $this->transform($item, $format);
    }, $items);
}

这篇关于array_map并将2个参数传递给映射函数-array_map():参数3应该是一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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