laravel二维数组转一维数组

在`laravel`中我们经常需要将二维数组转为一维数组,

如果直接写`foreach`会比较笨重

有没有简单的方法

比如,我们想将以下二维数组

```
$arr = array(
[ 'name' => "username1", "email" => "username1@qq.com"],
[ 'name' => "username2", "email" => "username2@qq.com"],
[ 'name' => "username3", "email" => "username3@qq.com"],
);
```
转化成
```
$data = array( "username1" => "username1@qq.com", "username2" => "username2@qq.com", "username3" =>"username3@qq.com" );
```

方法一:

`$data = array_column($arr,'email','name');`

方法二:

`$data = collect($arr)->pluck("email","name");`

方法三:
```
$data = collect($arr)->reduce(function($lookup,$item){
$lookup[$item["name"]] = $item["email"]; return $lookup;
},[]);
```

    A+
发布日期:2020年11月29日  所属分类:未分类

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: