Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用php将嵌套JSON与关系导入MySQL_Php_Mysql_Arrays_Json - Fatal编程技术网

使用php将嵌套JSON与关系导入MySQL

使用php将嵌套JSON与关系导入MySQL,php,mysql,arrays,json,Php,Mysql,Arrays,Json,我正在寻找一种简单的解决方法,将现有的嵌套JSON数据导入几个MySQL表。JSON没有双向关系,所以我认为它们应该自动生成 以下是一个数据示例: [ { "targetgroup": "Staff", "plan": "this field just exists and should be ignored in database", "budgetlevel": "Government", "spots": 5,

我正在寻找一种简单的解决方法,将现有的嵌套JSON数据导入几个MySQL表。JSON没有双向关系,所以我认为它们应该自动生成

以下是一个数据示例:

[
    {
        "targetgroup": "Staff",
        "plan": "this field just exists and should be ignored in database",
        "budgetlevel": "Government",
        "spots": 5,
        "edutype": "Bachelor",
        "qualilevel": "Specialist",
        "speciality": "Mathematician",
        "qualification": "Finished",
        "faculty": "Applied mathematics",
        "institute": "this field is sometimes empty in input data",
        "eduform": "Full-time",
        "profiles": [
            "Jr. Arithmetic manager"
        ],
        "entrancetests": [
            {
                "subject": "math",
                "typeoftest": "GOV",
                "minscore": "37",
                "ratingtype": "out of 100"
            },
            {
                "subject": "language",
                "typeoftest": "GOV",
                "minscore": "27",
                "ratingtype": "out of 100"
            },
            {
                "subject": "physics",
                "typeoftest": "GOV",
                "minscore": "40",
                "ratingtype": "out of 100"
            }
        ]
    },
  {
        "targetgroup": "Educational workers",
        "plan": "fridge",
        "budgetlevel": "Legacy",
        "spots": 26,
        "edutype": "Bachelor",
        "qualilevel": "Master",
        "speciality": "Data analysis",
        "qualification": "Finished",
        "faculty": "Machine learning mathematics",
        "institute": "",
        "eduform": "Full-time",
        "profiles": [
            "Head counting manager"
        ],
        "entrancetests": [
            {
                "subject": "Discrete mathematics",
                "typeoftest": "GOV",
                "minscore": "32",
                "ratingtype": "Out of 100"
            },
            {
                "subject": "Algorythm theory",
                "typeoftest": "GOV",
                "minscore": "51",
                "ratingtype": "Out of 100"
            },
            {
                "subject": "Advanced exception catching",
                "typeoftest": "GOV",
                "minscore": "56",
                "ratingtype": "Out of 100"
            }
        ]
    }
]
数据库结构:

表“dep:”

id(自动增量)|目标组|预算级别|点|教育类型。。。etc,与JSON字段名相同

表格“配置文件”

id(相对于相应的父块)|名称

表“入口测试”:

id(相对于相应的父块)|主题|测试类型| minscore |评级类型


关于如何导入非嵌套JSON,我有一个大致的想法,但我很难弄清楚如何添加关系,如何在循环中定义父块?提前谢谢。

圣诞快乐,mkrl。我们实际上不应该为任何人编写新代码,我们只是想修复现有的编码尝试。然而,今天我想通过实践来了解更多关于pdo的知识,而你的问题恰好是受益者。下面是一个功能齐全的事务性pdo流程,适用于您的具体情况。我已经在我的服务器上测试了3个与您的结构匹配的MyISAM表。现在,有可能你现在不喜欢pdo;如果没有,我希望我的提议将迫使您尝试一些新的东西,并使您查询数据库的方式现代化

$json='[
    {
        "targetgroup": "Staff",
        "plan": "this field just exists and should be ignored in database",
        "budgetlevel": "Government",
        "spots": 5,
        "edutype": "Bachelor",
        "qualilevel": "Specialist",
        "speciality": "Mathematician",
        "qualification": "Finished",
        "faculty": "Applied mathematics",
        "institute": "this field is sometimes empty in input data",
        "eduform": "Full-time",
        "profiles": [
            "Jr. Arithmetic manager"
        ],
        "entrancetests": [
            {
                "subject": "math",
                "typeoftest": "GOV",
                "minscore": "37",
                "ratingtype": "out of 100"
            },
            {
                "subject": "language",
                "typeoftest": "GOV",
                "minscore": "27",
                "ratingtype": "out of 100"
            },
            {
                "subject": "physics",
                "typeoftest": "GOV",
                "minscore": "40",
                "ratingtype": "out of 100"
            }
        ]
    },
  {
        "targetgroup": "Educational workers",
        "plan": "fridge",
        "budgetlevel": "Legacy",
        "spots": 26,
        "edutype": "Bachelor",
        "qualilevel": "Master",
        "speciality": "Data analysis",
        "qualification": "Finished",
        "faculty": "Machine learning mathematics",
        "institute": "",
        "eduform": "Full-time",
        "profiles": [
            "Head counting manager"
        ],
        "entrancetests": [
            {
                "subject": "Discrete mathematics",
                "typeoftest": "GOV",
                "minscore": "32",
                "ratingtype": "Out of 100"
            },
            {
                "subject": "Algorythm theory",
                "typeoftest": "GOV",
                "minscore": "51",
                "ratingtype": "Out of 100"
            },
            {
                "subject": "Advanced exception catching",
                "typeoftest": "GOV",
                "minscore": "56",
                "ratingtype": "Out of 100"
            }
        ]
    }
]';


$db=new PDO("mysql:host=yourhost;dbname=yourdbname;charset=utf8","username","password");

try{
    $db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);  // this will deny subsequent queries from being executed if there is an error and permit exception handle at the bottom
    $db->beginTransaction();

    // dep
    $dep_cols=array("targetgroup","budgetlevel","spots",
        "edutype","qualilevel","speciality","qualification",
        "faculty","institute","eduform");  // declare columns
    $dep_keys=array_map(function($v){return ":$v";},$dep_cols);  // build :keys    
    $dep_cols=array_combine($dep_keys,$dep_cols);   // assign :keys
    var_export($dep_cols);
    $dep_query="INSERT INTO `dep` (`".implode('`,`',$dep_cols)."`)"; // list columns as csv
    $dep_query.=" VALUES (".implode(',',array_keys($dep_cols)).");";
    echo "<div>$dep_query</div>";
    $stmt_add_dep=$db->prepare($dep_query);

    // profile
    $profile_cols=array('name');
    $profile_query="INSERT INTO `profile` (`id`,`".implode('`,`',$profile_cols)."`)"; // list columns as csv
    $profile_query.=" VALUES (LAST_INSERT_ID(),".implode(',',array_fill(0,sizeof($profile_cols),"?")).");";
    echo "<div>$profile_query</div>";

    // entrancetests
    $entrance_cols=array('subject','typeoftest','minscore','ratingtype');  // declare columns
    $entrance_keys=array_map(function($v){return ":$v";},$entrance_cols);  // build :keys
    $entrance_cols=array_combine($entrance_keys,$entrance_cols);  // assign :keys    
    var_export($entrance_cols);
    $entrance_query="INSERT INTO `entrancetests` (`id`,`".implode('`,`',$entrance_cols)."`)"; // list columns as csv
    $entrance_query.=" VALUES (LAST_INSERT_ID(),".implode(',',array_keys($entrance_cols)).");";
    echo "<div>$entrance_query</div>";
    $stmt_add_entrance=$db->prepare($entrance_query);

    foreach(json_decode($json) as $d){
        foreach($dep_cols as $k=>$v){
            $stmt_add_dep->bindValue($k,(property_exists($d,$v)?$d->$v:""));
            echo "<div>$k => {$d->$v}</div>";
        }
        $stmt_add_dep->execute();
        echo "<div>Dep Affected Rows: ",$stmt_add_dep->rowCount(),"</div><br>";

        $stmt_add_profile=$db->prepare($profile_query);
        foreach($d->profiles as $k=>$v){
            $stmt_add_profile->bindValue($k+1,$v);
            echo "<div>",$k+1," => $v</div>";
        }
        $stmt_add_profile->execute();
        echo "<div>Profile Affected Rows: ",$stmt_add_profile->rowCount(),"</div><br>";

        foreach($d->entrancetests as $o){
            foreach($entrance_cols as $k=>$v){
                $stmt_add_entrance->bindValue($k,(property_exists($o,$v)?$o->$v:""));
                echo "<div>$k => {$o->$v}</div>";
            }
        }
        $stmt_add_entrance->execute();
        echo "<div>Entrance Affected Rows: ",$stmt_add_entrance->rowCount(),"</div><br>";
    }

    // $db->commit();  // Only use with InnoDB tables.  MyISAM is auto-commit

}
catch(PDOException $e){
    // $db->rollBack();  // Only works if InnoDB table.  If MyISAM table, it doesn't rollback.
    echo "Error message: {$e->getMessage()}. File: {$e->getFile()}. Line: {$e->getLine()}";
    // do not show these error messages to users when you go live
}
$json=”[
{
“目标集团”:“员工”,
“计划”:“此字段在数据库中仅存在,应忽略”,
“预算级别”:“政府”,
"斑点":五,,
“教育类型”:“学士”,
“资格等级”:“专家”,
“专业”:“数学家”,
“资格”:“完成”,
“教员”:“应用数学”,
“institute”:“此字段在输入数据中有时为空”,
“教育形式”:“全职”,
“概况”:[
“小算术经理”
],
“入学考试”:[
{
“科目”:“数学”,
“测试类型”:“GOV”,
“minscore”:“37”,
“评级类型”:“100分之一”
},
{
“主题”:“语言”,
“测试类型”:“GOV”,
“minscore”:“27”,
“评级类型”:“100分之一”
},
{
“主题”:“物理学”,
“测试类型”:“GOV”,
“minscore”:“40”,
“评级类型”:“100分之一”
}
]
},
{
“目标群体”:“教育工作者”,
“计划”:“冰箱”,
“预算级别”:“遗产”,
“斑点”:26,
“教育类型”:“学士”,
“资格等级”:“大师级”,
“专业”:“数据分析”,
“资格”:“完成”,
“教员”:“机器学习数学”,
“学会”:“学会”,
“教育形式”:“全职”,
“概况”:[
“人头计数经理”
],
“入学考试”:[
{
“主题”:“离散数学”,
“测试类型”:“GOV”,
“minscore”:“32”,
“评级类型”:“100分之一”
},
{
“主题”:“算法理论”,
“测试类型”:“GOV”,
“minscore”:“51”,
“评级类型”:“100分之一”
},
{
“主题”:“高级异常捕获”,
“测试类型”:“GOV”,
“minscore”:“56”,
“评级类型”:“100分之一”
}
]
}
]';
$db=newpdo(“mysql:host=yourhost;dbname=yourdbname;charset=utf8”、“用户名”、“密码”);
试一试{
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);//如果出现错误,将拒绝执行后续查询,并允许在底部执行异常句柄
$db->beginTransaction();
//副署长
$dep_cols=数组(“目标组”、“预算级别”、“点”,
“教育类型”、“资格等级”、“专业”、“资格”,
“教员”、“学院”、“教育形式”);//声明列
$dep_keys=array_map(函数($v){return:$v”;},$dep_cols);//构建:keys
$dep_cols=array_combine($dep_keys,$dep_cols);//分配:keys
var_出口($dep_cols);
$dep_query=“插入到`dep`(`).introde(`,`,$dep_cols)。“`”;//将列列列为csv
$dep_query.=“值(“.introde(',”,数组键($dep_cols))”;
回显“$dep_query”;
$stmt\u add\u dep=$db->prepare($dep\u query);
//侧面图
$profile_cols=数组('name');
$profile_query=“INSERT INTO`profile`(`id`,`)。内爆(`,`,$profile_cols)。“`)”;//将列列列为csv
$profile\U query.=“值(最后一个插入的ID(),”。内爆(“,”,数组填充(0,sizeof($profile\U cols),“?”));”;
回显“$profile_query”;
//入学考试
$entrance\u cols=array('subject','typeoftest','minscore','ratingtype');//声明列
$entrance\u keys=array\u map(函数($v){return:$v”;},$entrance\u cols);//构建:键
$entrance\u cols=array\u combine($entrance\u keys,$entrance\u cols);//分配:keys
var_出口(进口成本);
$entrance\u query=“插入到`entrantests`(`id`,`)。内爆(`,`,$entrance\u cols)。“`);//将列列作为csv列出
$entrance\u query.=“值(最后一次插入\u ID(),”.内爆(“,”,数组\u键($entrance\u cols))”;”;
回显“$entrance\u query”;
$stmt\u add\u entrance=$db->prepare($entrance\u query);
foreach(json_解码($json)为$d){
foreach($k=>v){
$stmt_add_dep->bindValue($k,(属性_存在($d,$v)?$d->$v:);
回显“$k=>{$d->$v}”;
}
$stmt_add_dep->execute();
echo“Dep受影响的行:”,$stmt\u add\u Dep->rowCount(),“
”; $stmt\u add\u profile=$db->prepare($profile\u query); foreach($d->profiles as$k=>v){ $stmt\u add\u profile->bindValue($k+1,$v); 回声“$k+1”,=>$v”; } $stmt\u添加\u profi