如何将Json关联数组存储到mysql

时间:2013-07-26 16:47:46

标签: php mysql json

我有来自Web服务的JSon数据,我使用

将其解码为关联数组
$data = json_decode($postdata, true);

using print_r($data);

阵列

(
  [0] => Array
        (
            [id] => 1
            [cityName] => London
            [cityState] => London
            [cityPopulation] => 8173194
            [country] => United Kingdom
        )

    [1] => Array
        (
            [id] => 2
            [cityName] => Bombay
            [cityState] => Maharashtra
            [cityPopulation] => 12478447
            [country] => India
        )

    [2] => Array
        (
            [id] => 3
            [cityName] => Kuala Lumpur
            [cityState] => Federal Territory
            [cityPopulation] => 1627172
            [country] => Malaysia
        )

    [3] => Array
        (
            [id] => 4
            [cityName] => New York
            [cityState] => New York
            [cityPopulation] => 8336697
            [country] => United States
        )

    [4] => Array
        (
            [id] => 5
            [cityName] => Berlin
            [cityState] => Berlin
            [cityPopulation] => 3538652
            [country] => Deutschland
        )

)

我想将每个四个数组中的每个id,cityName,cityName,cityState,cityPopulation,country插入到现有的mysql数据库中。

2 个答案:

答案 0 :(得分:2)

$db = new PDO(...);
$query = $db->prepare("INSERT INTO mytable "
         ."(id, cityName, cityState, citypopulation,country) "
         ."VALUES (:id, :cityName, :cityState, :cityPopulation, :country)");

foreach ($data as $entry){
    foreach ($entry as $column => $value){
      $query->bindParam(':' . $column, $value);
    }
    $query->execute($entry);
}

或者那种性质......

答案 1 :(得分:0)

您可以将其编码为字符串。查看messagePack(http://msgpack.org/)。这是一个非常轻量级的编码。