array_map and pass 2 arguments to the mapped function - array_map(): Argument #3 should be an array(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 应该是一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:array_map 并将 2 个参数传递给映射函数 - array_map():参数 #3 应该是一个数组
				
        
 
            
        基础教程推荐
- Yii2 - 在运行时设置邮件传输参数 2022-01-01
 - php中的PDF导出 2022-01-01
 - php中的foreach复选框POST 2021-01-01
 - php 7.4 在写入变量中的 Twig 问题 2022-01-01
 - 将变量从树枝传递给 js 2022-01-01
 - Web 服务器如何处理请求? 2021-01-01
 - 使用 scandir() 在目录中查找文件夹 (PHP) 2022-01-01
 - 主题化 Drupal 7 的 Ubercart “/cart"页 2021-01-01
 - 如何在数学上评估像“2-1"这样的字符串?产生“1"? 2022-01-01
 - PHPUnit 的 Selenium 2 文档到底在哪里? 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
				
				
				
				