douju4278 2012-10-30 09:13
浏览 37

从csv到数据库获取层次结构的最简洁方法是什么?

In a web app my users upload a csv file and I need to check it on the way into the database. Part of the information forms a simple hierarchical dataset, so I want to make sure that rows are unique. Here's what I was thinking of doing, with an example.

CSV includes these rows...

field5      field6      field7
fred        bert        apple
fred        bert        apple
fred        george
fred        george      pear
will        tom         orange
will        tom         plum

I was going to absorb them into a PHP array like this.

$unique_fields = array();
while( $row = fgetcsv($handle) ){
    if( $row[5] ){
        if( !array_key_exists( $row[5] , $unique_fields ) ){
            $unique_fields[ $row[5] ] = array();
        }
        if( $row[6] ){
            if( !array_key_exists( $row[6] , $unique_fields[ $row[5] ] )){
                $unique_fields[ $row[5] ][ $row[6] ] = array();
            }

            if( $row[7] ){
                if( !array_key_exists( $row[7], $unique_fields[ $row[5] ][ $row[6] ]  )){
                    $unique_fields[ $row[5] ][ $row[6] ][ $row[7] ] = array();
                }
            }
        }
    }
}

If this is a good idea (and I'm open to suggestions) - what's the best way after that? I want to transfer the array into my database so that it looks like the csv example above, but without duplicates.

  • 写回答

1条回答 默认 最新

  • douxian9010 2012-10-30 11:24
    关注

    OK, no one wanted a stab at it, so I persevered and this is what I came up with. I'll watch the page in case someone has a better solution. Thanks for looking.

    if( count($unique_fields) ){
        foreach( $unique_fields as $k1=>$v1 ){
            if( is_array($v1) ){
                foreach( $v1 as $k2=>$v2 ){
                    if( is_array($v2) ){
                        foreach( $v2 as $k3=>$v3 ){
                            //insert $k1, $k2, $k3
                        }
                    }else{
                        //insert $k1, $k2
                    }
                }
            }else{
                //insert $k1 on its own
            }
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度