对象内的数组|数据库插入

时间:2017-11-19 16:34:05

标签: javascript php arrays mongodb object

我有以下对象数组。目前它有一个对象包含几个内部。

let arr = 
    [
     {
        "data": {
            "Score": {
                "score": [
                    "87",
                    "21"
                ],
                "Player": [
                    "Wiki",
                    "Tim"
                ]
            },
            "Designation": {
                "By": [
                    "0",
                    "0",
                    "1",
                    "0",
                    "0"
                ],
                "Position": [
                    "31/07/17",
                    "31/07/17",
                    "31/07/17",
                    "31/07/17",
                    "31/07/17"
                ]
            },
            "Address": {
                "Location": "London",
                "House_No": "43-B",
            }
        }
    }
]

以上数据将放在一个表格中。

我试过循环并插入但没有任何出路。上面的数据不是常数意味着会像Position那样改变有5个元素,下次可能是6,所以我不能简单地通过索引插入它。

我尝试过但没有成功。

3 个答案:

答案 0 :(得分:0)

Mysql可以存储json数据,你可以在获取之后进行解析,甚至你可以从mysql查询中解析json数据,但是如果数据发生变化那就很复杂,所以最好存储它,获取和解析。 您可以选择feild type JSON并在其中存储json。

CREATE TABLE `book` (
  `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(200) NOT NULL,
  `tags` json DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;

你可以使用php函数在其中插入json数据: -

$json_data = json_encode($json_data);

插入命令将是: -

INSERT INTO `book` (`title`, `tags`)
VALUES (
  'ECMAScript 2015: A SitePoint Anthology',
  '$json_data'
);

对于通过mysql查询操作json数据,有几个函数,如JSON_ARRAY(),JSON_OBJECT()等,您可以更喜欢使用它们。有关详细信息,请参阅以下文章: - https://www.sitepoint.com/use-json-data-fields-mysql-databases/

答案 1 :(得分:0)

在Mongodb中,如果您有动态数据,可以使用如下所示的混合类型模式: -

details:Schema.Types.Mixed,

示例架构: -

// grab the things we need
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var mongoosePaginate = require('mongoose-paginate');
// create a schema
var casesSchema = new Schema({
    sku: {type:String, unique:true},
    details:Schema.Types.Mixed,
    created_at: {type:Date, default: Date.now},
    images: Schema.Types.Mixed,
    ebay_hosted_images: Schema.Types.Mixed,
    cloudinary_hosted_images: Schema.Types.Mixed,
    dropbox_hosted_images: Schema.Types.Mixed,
    is_listed:Boolean,
    user_id : {type: String, ref:'User'}
});
casesSchema.plugin(mongoosePaginate);
var cases = mongoose.model('cases', casesSchema);

module.exports = cases;

答案 2 :(得分:-1)

ES6 中,您只需获得如下对象的所有键和值:
Object.keys(myObj).forEach(key => { console.log(key); // the name of the current key. console.log(myObj[key]); // the value of the current key. });

如果是每个用途的数组,则获取所有值 arr.forEach(function(element) { console.log(element); });

arr.push(element)用于将元素推送到数组的最后一个索引。

相关问题