ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[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); } ) ); ~~~