繁体   English   中英

将JSON解析为MySQL表

[英]Parsing JSON to MySQL table

我正在使用Zend Framework(1.12),并且想基于JSON文件创建一个表。 我已经创建了表及其字段(现在它们都是长文本),它所要做的就是将它们插入正确的列中。 我遵循以下示例:

http://www.daniweb.com/web-development/php/threads/381669/json-to-mysql-with-php (第二篇文章)将JSON解析为mySQL

问题是我的JSON的构造不同(我的JSON中有一个叫做Actie的“根元素”,实际上不知道正确的术语),它包含一个包含所有对象的数组。 目前,我正在使用以下代码:

$actieurl = "http://creative3s.com/thomas/nmdad/actie.json";
        $my_arr = json_decode(file_get_contents($actieurl));

        $db = new Zend_Db_Adapter_Pdo_Mysql(array(
            'host' => 'localhost',
            'username' => 'root',
            'password' => NULL,
            'dbname' => 'zf-tutorial'
            ));

        foreach($my_arr as $key => $value){
            $sql[] = (is_numeric($value)) ? "`$key` = $value" : "`$key` = '" . mysql_real_escape_string($value) . "'"; 
        }

        $sqlclause = implode(",",$sql);
        $query = "INSERT INTO `testerdetest` SET $sqlclause";
        $db->query($query);

但是我收到一个错误消息,说我正在传递一个数组:

Warning: mysql_real_escape_string() expects parameter 1 to be string, array given in C:\Users\Thomas\Documents\GitHub\NMDAD-testing\application\controllers\IndexController.php on line 29

有谁知道如何使用这种格式的JSON解决此问题? 请记住,我无法以任何方式更改JSON。 额外链接:

JSON: http//creative3s.com/thomas/nmdad/actie.json表结构: http//i.imgur.com/KtXeEuw.png

您的json数据具有顶级键'Actie',因此您需要遍历$my_arr->Actie

您可以将代码简化为:

$actieurl = "http://creative3s.com/thomas/nmdad/actie.json";
$my_arr = json_decode(file_get_contents($actieurl));

$db = new Zend_Db_Adapter_Pdo_Mysql(array(
    'host' => 'localhost',
    'username' => 'root',
    'password' => NULL,
    'dbname' => 'zf-tutorial'
));

foreach($my_arr->Actie as $row){
    $db->insert('testerdetest', (array)$row);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM