V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
atan
V2EX  ›  PHP

如何高效的分割一个数组

  •  
  •   atan · 2014-07-03 13:11:07 +08:00 · 3084 次点击
    这是一个创建于 3590 天前的主题,其中的信息可能已经有所发展或是发生改变。
    现有一个大约50W行的文本文件,使用 `file('file.txt')` 取出内容后,需要按50个一组存入数据库,基本想法是用array_chunk分割后json_encode写入数据库,但是array_chunk一操作就提示内存超出上限,我知道PHP本身数组的内存效率就不高,有什么办法在不增加内存的情况下高效的分割这个文件?
    PS: memory_limit = 128M
    13 条回复    2014-07-05 11:52:08 +08:00
    TimeLe
        1
    TimeLe  
       2014-07-03 13:14:17 +08:00
    边读取 边入库操作 可否?
    breeswish
        2
    breeswish  
       2014-07-03 13:15:55 +08:00
    按行读取文件内容,每读满50个就存进去

    不要一次性全读入再一次性全分割再一次性存进去..&#$^@(*
    atan
        3
    atan  
    OP
       2014-07-03 13:17:10 +08:00
    @TimeLe 谢谢,这个我试过,但效率很低,而且内存占用很高
    shiny
        4
    shiny  
       2014-07-03 13:18:00 +08:00
    边读边入库+1,可以考虑 fgets,文件大的时候很有用。
    atan
        5
    atan  
    OP
       2014-07-03 13:25:35 +08:00
    @shiny
    @breeswish 谢谢,试试看去
    bearcat001
        6
    bearcat001  
       2014-07-03 13:47:02 +08:00
    1. 大文件都是按行读的,读够50条,将50条写成一条SQL存入数据库
    2. 或者边读边写生成一个格式化的文件文件用LOAD DATA来存入数据库
    TimeLe
        7
    TimeLe  
       2014-07-03 13:51:25 +08:00
    @bearcat001 LZ貌似说这种效率底下 内存占用高
    bearcat001
        8
    bearcat001  
       2014-07-03 14:02:21 +08:00
    @TimeLe 方法1是最省内存的,1+50的内存占用,存储效率适中
    方法2只需要1的占用,存储效率较高

    我之前测试过这几种方法,具体看这里
    http://yansu.org/2014/04/16/insert-large-number-of-data-in-mysql.html
    Tonni
        9
    Tonni  
       2014-07-03 14:08:48 +08:00
    楼主博客主题是什么?
    TimeLe
        10
    TimeLe  
       2014-07-03 15:37:31 +08:00
    @bearcat001 恩.已看 顺便博客写的不错
    atan
        11
    atan  
    OP
       2014-07-03 15:52:51 +08:00
    @Tonni Typecho 默认就是这个样子的
    Actrace
        12
    Actrace  
       2014-07-04 00:15:03 +08:00
    打开文件句柄后使用fseek手动完成行切操作,这样你就可以控制每次读入的长度,并且不占用大量内存。
    xieranmaya
        13
    xieranmaya  
       2014-07-05 11:52:08 +08:00
    才50万行,一边读一边写,用py啊,分分钟就ok了。
    我做过5万多行的,需求跟你一模一样,不过一行特别长,文件总大小100M+,几秒钟就搞定了
    还有py代码呢,我来找找

    import os
    import sys
    import platform

    print(platform.python_version())
    lpf = 4000 # line per file
    bigfile = open('bigfile.txt',encoding='utf8')
    part = 10 # 为了文件名长度一致
    while True:
    parts = open(str(part)+'.dat','w',encoding='utf8')
    part += 1
    for i in range(0,lpf):
    line = bigfile.readline()
    if not line:
    parts.close()
    bigfile.close()
    sys.exit()
    parts.write(line)
    parts.close()

    bigfile.close()
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   948 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 18:50 · PVG 02:50 · LAX 11:50 · JFK 14:50
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.