多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] 如何优化这种数据结构,用于存入到数据库中 原始数据结构 ~~~ [ [ "group"=>"A", "list"=>[ ["name"=>"1"], ["name"=>"2"], ["name"=>"3"], ] ], [ "group"=>"B" "list"=>[ ["name"=>"4"], ["name"=>"5"], ["name"=>"6"], ] ] ] ~~~ 转化后的数据结构 ~~~ [ ["group"=>"A","name"=>"1"], ["group"=>"A","name"=>"2"], ["group"=>"A","name"=>"3"], ["group"=>"B","name"=>"4"], ["group"=>"B","name"=>"5"], ["group"=>"B","name"=>"6"], ] ~~~ # 解决一 ~~~ $data = [ [ "group" => "A", "list" => [ ["name" => "1"], ["name" => "2"], ["name" => "3"], ] ], [ "group" => "B", "list" => [ ["name" => "4"], ["name" => "5"], ["name" => "6"], ] ] ]; dd(collect($data)->flatMap(function ($data) { return collect($data['list'])->map(function ($item) use ($data) { return ['group' => $data['group'], 'name' => $item['name']]; }); })->toArray()); ~~~ # 解决二 ~~~ $demo = [ ["group"=>"A", "list"=>[ ["name"=>"1"], ["name"=>"2"], ["name"=>"3"],] ], ["group"=>"B", "list"=>[ ["name"=>"4"], ["name"=>"5"], ["name"=>"6"],] ] ]; $middle = ''; dd( collect($demo)->flatten()->map( function($val) use(&$middle){ if(is_numeric($val)) { return ['name'=>$val,'group'=>$middle]; }else{ $middle = $val; } })->reject( function($val){ return !is_array($val); } ) ); ~~~