array_map 并将 2 个参数传递给映射函数 - array_map():参数 #3 应该是一个数组

2022-01-08 00:00:00 php laravel laravel-4

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

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);
}

相关文章