Laravel 将数据行转换为1个对象

Laravel 将数据行转换为1个对象,laravel,collections,Laravel,Collections,阅读拉威尔6行 {"filter_options":[ {"id":5,"key":"category_id","value":"2","created_at":"2020-02-10 18:23:48"}, {"id":4,"key":"only_with_images","value":"1","created_at":"2020-02-10 18:23:48"} ] } 我需要转换1个对象中的数据,如 { category_id : 2, only_w

阅读拉威尔6行

 {"filter_options":[
   {"id":5,"key":"category_id","value":"2","created_at":"2020-02-10 18:23:48"},
   {"id":4,"key":"only_with_images","value":"1","created_at":"2020-02-10 18:23:48"}
  ]
 } 
我需要转换1个对象中的数据,如

{ 
   category_id : 2,
   only_with_images :"1"
}
我知道如何用一个公共圆来实现这一点,但是否有一些集合映射方法可以实现这一点


谢谢

我不确定您的数据是否是一个集合,但我们假设这就是数据

$array=['filter\u options'=>[
['id'=>5,'key'=>category\u id','value'=>2,'created\u'at'=>2020-02-1018:23:48'],
['id'=>4,'key'=>'仅包含图像,'value'=>1,'created'=>2020-02-1018:23:48'],
]];
你只需要这样做

//在PHP7.4之后
return collect($array['filter_options'])->flatMap(fn($item)=>[$item['key']=>$item['value']);
//PHP7.4之前
返回集合($array['filter_options')->flatMap(函数($item){
返回[$item['key']=>$item['value'];
});
注意:显然这是访问属性的数组语法(
$item['key']
),如果您的数据来自laravel eloquent,您可能不需要
collect()
助手方法,您需要使用对象方式访问属性,如
$item->key