将JSON解析为MySQL表 [英] Parsing JSON to MySQL table

查看:185
本文介绍了将JSON解析为MySQL表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using Zend Framework (1.12) and I'd like to create a table based on a JSON file. I've already created the table and its fields (they're all longtext for now), all it has to do is insert them into the right columns. I followed these examples:

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

问题是我的JSON的构造不同(我的JSON具有一个称为Actie的根元素",并不真正知道正确的术语),它包含一个包含所有对象的数组.目前,我正在使用以下代码:

The problem is that my JSON is constructed differently (mine has a "root element" called Actie, don't really know the right term) which contains an array with all the objects. Currently, I'm using this code:

$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);

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

But I'm getting an error saying that I'm passing an array:

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.额外链接:

Does anyone know how to solve this with a JSON of this format? Keep in mind that I cannot alter the JSON in any way. Extra links:

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

JSON: http://creative3s.com/thomas/nmdad/actie.json Table structure: http://i.imgur.com/KtXeEuw.png

推荐答案

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

Your json data has the top level key 'Actie', so you need to be looping through $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);
}

这篇关于将JSON解析为MySQL表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆