laravel array_map 得到错误“array_map():参数 #2 应该是一个数组”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33605503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:39:39  来源:igfitidea点击:

laravel array_map get error "array_map(): Argument #2 should be an array"

arrayslaravelhas-many

提问by monoy suronoy

I'm new on laravel. Why I'm always get error:

我是 Laravel 的新手。为什么我总是收到错误:

array_map(): Argument #2 should be an array ?

array_map():参数#2 应该是一个数组?

whereas I'm assigning parameter array on this method?

而我在这个方法上分配参数数组?

this is my example code :

这是我的示例代码:

$products = Category::find(1)->products;

note : 1 category has many products

注意:1个类别有很多产品

this is the array from query :

这是来自查询的数组:

[{
   "id": "1",
   "name": "action figure",
   "created_at": "2015-11-09 05:51:25",
   "updated_at": "2015-11-09 05:51:25"
    }, {
    "id": "2",
    "name": "manga",
    "created_at": "2015-11-09 05:51:25",
    "updated_at": "2015-11-09 05:51:25"
}]

when I'm trying the following code:

当我尝试以下代码时:

$results = array_map( function($prod) {
    return $prod.name;
}, $products);

and I get the error like below:

我得到如下错误:

"array_map(): Argument #2 should be an array"

“array_map():参数#2 应该是一个数组”

回答by PeterPan666

You should write

你应该写

$results = array_map(function ($prod) {
    return $prod->name;
}, $products->toArray());

Because $productsis a Collection and not an array.

因为$products是一个集合而不是一个数组。

If you just want to have a list of product name use the pluckmethod

如果您只想获得产品名称列表,请使用该pluck方法

$results = $products->pluck('name')

In newer version of Laravel you should use $products->all();instead of toArraybecause in the case of an Eloquent collection, toArraywill try to convert your models to array too. allwill just return an array of your models as is.

在较新版本的 Laravel 中,您应该使用$products->all();而不是toArray因为在Eloquent集合的情况下,toArray也会尝试将您的模型转换为数组。all将按原样返回您的模型数组。

That being said, since you are on a Collection you can also use the mapmethod on it like so (which is exactly the same as using pluckin your case)

话虽如此,既然你在一个集合上,你也可以map像这样使用它的方法(这与pluck在你的情况下使用完全相同)

$products->map(function ($product) {
    return $product->name;
});