1

我有一个关于 JSON 和 MySQL 数据库的问题。我想要的是我可以将 JSON 文件中的数据加载到我的数据库中的字段中。我的 JSON 文件如下所示:

{
    "wijken": {
        "11": {
            "id": "kml_1",
            "fid": "0",
            "wijziging": "Ja",
            "nieuwnr": "11",
            "naam": "Noordoost",
            "wijk": "Kanaaldorpen en -zone",
            "wijknr": "11",
            "objectid": "1",
            "area": "0",
            "len": "0"
        },
        "12": {
            "id": "kml_2",
            "fid": "1",
            "wijziging": "Ja",
            "nieuwnr": "12",
            "naam": "Noordoost",
            "wijk": "Oostakker",
            "wijknr": "12",
            "objectid": "2",
            "area": "0",
            "len": "0"
        }
    }
}

我有一个带有字段的表“wijken”的数据库:

ID / FID / WIJZIGING / NIEUWNR / NAAM / WIJK / WIJKNR / OBJECTID / AREA / LEN

现在我希望 json 文件中的所有数据都出现在该表中。(php + javascript)

有人可以帮我开始吗?(或者提供一些好的搜索词的教程)

提前致谢!

4

2 回答 2

4

First you need to load the file from the filesystem

$json_string = file_get_contents('some/path/to/file.json');

Then you can turn the json string into a php array using json_decode

$data = json_decode($json_string, true); 

At this point you will be able to access the data to go into the wijken table with $data['wijken'].

In order to insert this data into a mysql database, you will need to use one of the php mysql extensions, either mysqli or PDO.

I will use mysqli for this example:

// first create a connection to your database
$mysqli = new mysqli('localhost', 'user', 'password', 'database_name');

// this insert query defines the table, and columns you want to update
$query = <<<SQL
INSERT INTO wijken ('ID', 'FID', 'WIJZIGING', 'NIEUWNR', 'NAAM', 'WIJK', 'WIJKNR', 'OBJECTID', 'AREA', 'LEN')
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
SQL;

$stmt = $mysqli->prepare($query);

// for each of the 'rows' of data in the json we parsed, we will insert each value
// into it's corresponding column in the database, and we are doing this using prepared
// statements.
foreach ($data['wijken'] as $key => $value) {
    $stmt->bind_param(
        // the types of the data we are about to insert: s = string, i = int
        'sissssiiii', 
        $value['id'],
        $value['fid'],
        $value['wijziging'],
        $value['nieuwnr'],
        $value['naam'],
        $value['wijk'],
        $value['wijknr'],
        $value['objectid'],
        $value['area'],
        $value['len']
    );

    $stmt->execute();
}

$stmt->close();

// close the connection to the database
$mysqli->close();
于 2013-01-12T18:14:06.367 回答
1

这将输出您的 json 键和值。

$jsonIterator = new RecursiveIteratorIterator(
    new RecursiveArrayIterator(json_decode($json, TRUE)),
    RecursiveIteratorIterator::SELF_FIRST);

foreach ($jsonIterator as $key => $val) {
    if(is_array($val)) {
        echo "$key:\n";
    } else {
        echo "$key => $val\n";
    }
}
于 2013-01-12T17:09:23.053 回答