Thinkphp6把json数据插入数据库

文章描述:

thinkphp6读取json文件数据循环插入数据到数据库表中

读取json文件

$fileName = '../public/static/json/categorys.json';

$string = file_get_contents($fileName);
$data = json_decode($string,true);

$str = $data['message'];

循环插入

foreach($str as $key=>$val){
            // 一级分类
            $data = [
                'cat_id'    =>'',
                'cat_name'  =>$val['cat_name'],
                'cat_pid'   =>$val['cat_pid'],
                'cat_level' =>$val['cat_level'],
                'cat_deleted'=>$val['cat_deleted'],
                'cat_icon'=>$val['cat_icon']
            ];
            Db::name('categorys')->insert($data);

            $children = $val['children'];
            if($children){
                foreach($children as $k=>$v){
                    // 二级分类
                    $datax = [
                        'cat_id'    =>'',
                        'cat_name'  =>$v['cat_name'],
                        'cat_pid'   =>$v['cat_pid'],
                        'cat_level' =>$v['cat_level'],
                        'cat_deleted'=>$v['cat_deleted'],
                        'cat_icon'=>$v['cat_icon'] || ''
                    ];
                    Db::name('categorys')->insert($datax);



                    if(isset($v['children'])){
                        foreach($v['children'] as $keyx => $valx){
                            $dataxx = [
                                'cat_id'    =>'',
                                'cat_name'  =>$valx['cat_name'],
                                'cat_pid'   =>$valx['cat_pid'],
                                'cat_level' =>$valx['cat_level'],
                                'cat_deleted'=>$valx['cat_deleted'],
                                'cat_icon'=>$valx['cat_icon'] || ''
                            ];
                            Db::name('categorys')->insert($dataxx);
                        }
                    }


                }
            }


        }

 

发布时间:2022/06/12

发表评论