将JSON解析为MySQL表

问题描述 投票:1回答:1

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

http://www.daniweb.com/web-development/php/threads/381669/json-to-mysql-with-php(第二篇文章)Parse JSON to 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

php mysql json zend-framework
1个回答
2
投票

您的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);
}
© www.soinside.com 2019 - 2024. All rights reserved.