很多網站的系統(tǒng)配置的數據庫結構是下面這種格式的枚尼,然后取出數據的時候是這樣的:[{key: "APPID", value: "APPID"}, {key: "AppSecret", value: "AppSecret"}]
,這樣給并不能友好的給前臺婿脸,我們需要將他轉化成{APPID: "APPID", AppSecret: "AppSecret"}
常規(guī)方法
$data = json_decode('[{"key": "APPID", "value": "APPID"}, {"key": "AppSecret", "value": "AppSecret"}]');
$newData = array();
foreach($data as $v){
foreach($v as $key=>$value){
$newData[$key] = $value;
}
}
echo json_encode($newData);
collect方法
$data = json_decode('[{"key": "APPID", "value": "APPID"}, {"key": "AppSecret", "value": "AppSecret"}]');
$newData = collect($data)->map(function ($item){
return collect($item)->pluck('value','key');
});
echo json_encode($newData);
利用collect省去了多層的循環(huán)面褐,代碼看起來更加優(yōu)雅
使用collect如果不是在laravel項目請先熟知如何將collect引用進來