如何将json结果插入WordPress表?

时间:2017-10-24 19:28:13

标签: javascript php mysql json wordpress

我在WordPress中有一个生成json的自定义页面,我想插入WordPress数据库中的自定义表格。我怎么能这样做?



{"horarios":[{"dia":"2017-10-25","hora_inicio":"17:00","hora_termino":"17:00"},{"dia":"2017-10-26","hora_inicio":"13:30","hora_termino":"16:00"}]}




感谢。

1 个答案:

答案 0 :(得分:0)

要将表的数据插入Wordpress自定义表中。

步骤1:将mysql表转换为json文件 https://www.csvjson.com/sql2json

步骤2:导出表格并粘贴到https://www.csvjson.com/sql2json

/**
 * Continents 
 */
SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `continents`
-- ----------------------------
DROP TABLE IF EXISTS `continents`;
CREATE TABLE `continents` (
  `code` char(2) NOT NULL COMMENT 'Continent code',
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT;

-- ----------------------------
-- Records of continents
-- ----------------------------
INSERT INTO `continents` VALUES ('AF', 'Africa');
INSERT INTO `continents` VALUES ('AN', 'Antarctica');
INSERT INTO `continents` VALUES ('AS', 'Asia');
INSERT INTO `continents` VALUES ('EU', 'Europe');
INSERT INTO `continents` VALUES ('NA', 'North America');
INSERT INTO `continents` VALUES ('OC', 'Oceania');
INSERT INTO `continents` VALUES ('SA', 'South America');
INSERT INTO `continents` VALUES ('??', NULL);

第3步:创建目录数据

步骤4.将json文件放入数据目录。

第5步:将以下代码放入插件主插件文件或任何其他内容中。

register_activation_hook(__FILE__, 'plugin_name_install_data');

function plugin_name_install_data()
{
    global $wpdb;

    $table_name = $wpdb->prefix . 'continents'; 

    $contactjsondata = file_get_contents(plugin_dir_path( __FILE__ ) . 'data/continents.json');
    $data = json_decode($contactjsondata, true);

    foreach ($data['continents'] as $single_data) {

        $item=array(
            'code'=> $single_data['code'],
            'name' => $single_data['name']
        );

        $result = $wpdb->insert($table_name, $item);

    }
}