問題描述
將數據行轉換為 1 個對象 (Convert data rows to 1 object)
閱讀 Laravel 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"
}
我知道如何用一個普通的圓圈來實現,但是有一些收集映射方法?
謝謝!
參考解法
方法 1:
I am not sure if your data is a collection or not, but let's assume this is the data
$array = ['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'],
]];
you only need to do this
//after php 7.4
return collect($array['filter_options'])‑>flatMap(fn ($item) => [$item['key'] => $item['value']]);
//before php 7.4
return collect($array['filter_options'])‑>flatMap(function ($item) {
return [$item['key'] => $item['value']];
});
Note: obviously this is array syntax to access the properties($item['key']
), if your data soruce is from laravel eloquent, you may not need collect()
helper method and you need to use the object way to access the properties like $item‑>key
.
(by Petro Gromovo、Andy Song)