<?php // 换成你自己的json $str = '{"headers":{"student":["name","continent"]},"rows":{"student":[["Jane","America"],["Pascal","Europe"],["Xi","Asia"],["Jack","America"]]}}'; $a = json_decode($str, true); if (!isset($a['headers']) || !is_array($a['headers'])) { die("invalid json"); } foreach ($a['headers'] as $dbname => $colnameArr) { $colnames = implode(',', $colnameArr); $sql = "insert into {$dbname} ({$colnames}) values"; foreach ($a['rows'][$dbname] as $rowArr) { $rows = implode('\',\'', $rowArr); $sql .= "('{$rows}'),"; } $sql = rtrim($sql, ','); $sql .= ';'; echo $sql.PHP_EOL; }
// 本例输出
// insert into student (name,continent) values('Jane','America'),('Pascal','Europe'),('Xi','Asia'),('Jack','America');
参考资料:
http://www.showsql.com/2019/08/15/import-leetcode-json-into-mysql/