使用PHP代码将csv导入mongodb [英] Importing csv into mongodb using PHP code

查看:24
本文介绍了使用PHP代码将csv导入mongodb的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 MongoCollection::batchInsert() 将 csv 数据插入到 mongodb 中,

Im using MongoCollection::batchInsert() to insert csv data into mongodb,

<?php

$mongo = new Mongo("mongodb://192.168.1.7:27017");

$collection = $mongo->test->cartoons;
$row = 1;
 $handle = fopen(dirname(Yii::app()->request->scriptFile).'/images/importcsv/upload.csv', "r");
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
       echo "<p> $num fields in line $row: <br /></p>\n";
       $row++;
       $users = array();
       for ($c=0; $c < $num; $c++) {
            echo 'data--'.$data[$c] . "<br />\n";
        }
       $users[] =$data;
       var_dump($users);
       $collection->batchInsert($users);
    }
?>

上面的代码将数据作为两个单独的数组插入到 Mongo Collections 中,一行用于标头(CSV 标头),另一行用于数据.

the above code inserts data in Mongo Collections as two separate arrays one line for header(CSV header) and another one is for data.

现在我想将 CSV 标头与如下所示的数据合并以导入 mongo,

Now i want to merge the CSV header with data as like below to import in mongo,

{ "_id" : ObjectId("52c10f355b9e5cf00200014d"), "Name" : "Dhanam R.", "DOB" : "12-Aug-80", "Age" : "80" }

推荐答案

这个问题确实可以用一些谷歌搜索,但这一次,你要做的是获取 CSV 的第一行:

Really this question could use some Googling but this time only, what you do is take the first row of the CSV:

 $columns = fgetcsv($fh, 0, ',');
 $nrColumns = count($columns);
 for ($i=0; $i < $nrColumns; $i++)
 {
    if(array_key_exists($columns[$i], $columnsArray)){
        $columnsArray[$columns[$i].$col_inc] = $i;
        $col_inc++;
    }else{
        $columnsArray[$columns[$i]] = $i;
    }
 }

并使用它与 $c 中的索引进行比较:

And use that to compare to the index of what you have in $c:

 $user = array();
 for ($c=0; $c < $num; $c++) {
      $user[$columnsArray[$c]] = $data[$c]
      echo 'data--'.$data[$c] . "<br />\n";
  }

然后使用 $user 添加到数组中:

and then you use $user to add to the array:

$users[] =$user;

这篇关于使用PHP代码将csv导入mongodb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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