将 JSON 解析为 MySQL 表

2021-12-29 00:00:00 json php mysql zend-framework

我正在使用 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 构造不同(我的有一个名为 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:UsersThomasDocumentsGitHubNMDAD-testingapplicationcontrollersIndexController.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 数据具有顶级键 '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);
}

相关文章