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

查看:21
本文介绍了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-地图.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天全站免登陆