如何将每个嵌套的json放入sql中

时间:2016-09-01 00:18:31

标签: php mysql json

我有以下php完成

//read the json file contents
$jsondata = file_get_contents('ourfile.json');
 //convert json object to php associative array
$data = json_decode($jsondata, true);
//pull all job assignments 
$jobassignresults = array();
foreach($data['jobAssignments'] as $chunk){
    $jatech = $chunk['technician'];
    $jatechid = $jatech['id'];
    $jatechname = $jatech['name'];
    $jatechfinished = array($jatechid, $jatechname);
    $jobassignreults[] = $jatechfinished;
}
$jasplit = $data['jobAssignments']['split'];

我现在正在努力将这些数据放入mysql,并启动以下代码

$sql ="INSERT INTO table1(jobassignresults, 

我不能为我的生活弄清楚如何将每个技术列表列入sql数据库。

json看起来像这样

"jobAssignments": [
{
  "id": 15797,
  "jobId": 15792,
  "jobNumber": "15792",
  "technician": {
    "id": 156,
    "name": "Mike"
  },

1 个答案:

答案 0 :(得分:0)

如果有效,请尝试我的答案。我循环数据,然后为每个循环数据将其插入数据库。

//read the json file contents
$jsondata = file_get_contents('ourfile.json');
//convert json object to php associative array
$data = json_decode($jsondata, true);
//pull all job assignments 

$jobassignresults = array();
$jatech = array(); //initiate variable

foreach($data['jobAssignments'] as $chunk){
  $jatech = $chunk['technician'];
  $jatechid = $jatech['id'];
  $jatechname = $jatech['name'];
  $jatechfinished = array($jatechid, $jatechname);
  $jobassignreults[] = $jatechfinished;
}

foreach($jatech as $key => $techs) //loop every data and insert.
{
   $sql = "INSERT INTO table_name ('id','name') VALUES ($techs['id'], $techs['name']);";
}