【问题标题】:JSON to Database with phpJSON到数据库用php
【发布时间】:2015-12-14 13:06:19
【问题描述】:

所以我以这个 JSON 为例

    {  
  "top" : [
    {
      "info" : {
        "ID" : 0,
        "TID" : 1
      },
      "geo" : {
        "poins" : [
          [
            [
              -5.9,
              57.1
            ],
            [
              -5.99,
              57.0
            ]
          ]
        ]
      }
    },
    {
      "info" : {
        "ID" : 1,
        "TID" : 2
      },
      "geo" : {
        "points" : [
          [
            [
              -5.4,
              57.0
            ],
            [
              -5.9,
              57.0
            ]
          ]
        ]
      }
    }
   ]
}

我需要用 php 把这些信息放到数据库中 所以我在数据库中有一个名为 points 的列,它需要里面的数据看起来像:

[-5.4, 57.0],[-5.9, 57.0]

我有一个带有 ID 的列,所以我只需要为每个 ID 放入 JSON 中的点

我的 php 应该是这样的: 连接数据库

    $str = file_get_contents(the JSON);
            $json = json_decode($str, true); 
            foreach ($json['top'] as $field) {
                query='UPDATE poins_table
                SET points='$field['geo']['points']'
                 WHERE ID='$field['info']['ID']' '
        }

代码似乎不起作用。我错过了什么......任何建议都会有所帮助。谢谢

【问题讨论】:

  • 您的数据库连接在哪里?什么样的数据库?你有没有尝试过?
  • 我正在使用 MySQL,这不是连接问题。我需要的是从每个点获取信息,并使用 JSON 中的 id,所以它应该与 foreach 一起使用 ..其余的是没那么重要...

标签: php mysql json database


【解决方案1】:

您可以尝试以下操作:

<?php
$str = file_get_contents('the JSON URL');
$json = json_decode($str, true); 

try{
  $db = new PDO("dbtype:host=yourhost;dbname=yourdbname;charset=utf8","username","password");
  $query = $db->prepare('UPDATE poins_table SET points=? WHERE ID=?');

  foreach ($json['top'] as $field) {
    $query->execute(array(json_encode($field['geo']['points']), $field['info']['ID']));
  }
} catch(PDOException $e) {
   echo "Error: ". $e;
}
?>

【讨论】:

  • 如果这不是解决方案,它应该看起来如何......如果你只知道你有这个 JSON 并且你需要将它放在数据库中......你的代码会是什么样子
  • @ГеоргиДаскалов 抱歉,如果您不能从这里开始,我无法进一步帮助您。
猜你喜欢
  • 1970-01-01
  • 2018-09-19
  • 1970-01-01
  • 1970-01-01
  • 2015-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-30
相关资源
最近更新 更多