Search code examples
phplaravellaravel-4

array_map and pass 2 arguments to the mapped function - array_map(): Argument #3 should be an array


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(): Argument #3 should be an array

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.

Any ideas?


Solution

  • Please always read docs:

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

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

    and yet you pass bool $format as argument

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

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