2017-05-07 104 views
0

我:获得所有项目的集合mapWithKeys

$collection=Event::all(); 
$keyed = $collection->mapWithKeys(function ($item) { 
       return ['title' => $item['name'], 'start' => $item['event_date']]; 
    }); 

$keyed->all()被收集在改变键只返回最后一个项目:

Array 
(
    [title] => New Year 
    [start] => 2018-01-01 
) 

我如何获得与改变按键的所有活动?

+0

怎么办如果将'dd($ collection-> toArray());''放在'$ collection = Event :: all();'后面? – whoacowboy

+0

@whoacowboy'dd($ collection-> toArray());'given给出'array:3 [▼ 0 => array:5 [▼ “id”=> 1 “name”=>“Parent's Day” “event_date”=>“2018-02-14” ] 1 => array:5 [▼ “id”=> 2 “name”=>“Labor's Day \ n” “event_date”=>“2018 -05-01" ] 2 =>数组:5 [▼ “ID”=> 3 “名称”=> “新年” “EVENT_DATE”=> “2018年1月1日” ] ] '而'dd($ keyed-> toArray());'只给出最后一个事件。 – Steve

回答

1

mapWithKeys回调返回一个关联数组conaining一个键/值对,所以如果你只需要EVENT_DATE我建议采摘使用这样的:

$collection=Event::pluck('event_date', 'name'); 
+0

我需要'title'和'start'作为数组键,而不是'name'和'event_date'属性。 – Steve

+0

$ array = Event :: select('name as title','event_date as start') - > pluck('name','start'); – MohamedSabil83

相关问题