Laravel - 将数组推送到集合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49805963/
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
Laravel - push array to collection
提问by Aleks Per
I have this code where I try to grab all auth user categories:
我有这个代码,我尝试获取所有 auth 用户类别:
$cats = Auth::user()->cats()->lists('title','id');
and I want to add new data to $cats so I write:
我想向 $cats 添加新数据,所以我写:
$cats->push(['5','BMW']);
but I got:
但我得到了:
Collection {#459 ▼
#items: array:2 [▼
9 => "asd"
10 => array:2 [▼
0 => "5"
1 => "BMW"
]
]
}
How I to change my code to get this result:
我如何更改我的代码以获得此结果:
Collection {#459 ▼
#items: array:2 [▼
9 => "asd"
5 => "BMW"
]
}
So how I can add the array to this collection? p.s. I need this format because I use select2 jquery plugin
那么如何将数组添加到这个集合中呢?ps我需要这种格式,因为我使用select2 jquery插件
回答by Jonas Staudenmeir
You can use the collection like an array:
您可以像使用数组一样使用集合:
$cats[5] = 'BMW';
回答by Tarek Adam
I have played with it, and it doesn't look good, but here is something which might help you.
我玩过它,它看起来不太好,但这里有一些可能对你有帮助的东西。
$item = (object) ['id' => 5, 'val' => 'cat']
{#925 +"id": 5, +"val": "cat"}
collect([$item])
{#924 all: [ {#925 +"id": 5, +"val": "cat"}]}
collect([$item])->keyBy('id')->transform(
function($obj){ return $obj->val;
})
{#907 all: [5 => "cat"]}
So I think using keyBy()
and transform()
might get you where you're wanting to go.
所以我认为使用keyBy()
并且transform()
可能会让你到达你想去的地方。