douye2020 2014-03-16 23:05
浏览 64
已采纳

将CSV解析为数组并搜索该数组中的值

What I want to do is insert a 47kb csv file into an array in the following method.

CSV Structure:

ID;TEXT;INTEGER;VARCHAR(1)

Example: 1;Random Text;0;Q

But I have multiple id's in the CSV file because this is a question and answer table and for each question the answers have the same ID of the question.

What I pretend to do is to import the CSV file into an array, then search that array for Q in VARCHAR field, then count that to have the number of questions(Q = question, A = answer).

Having the number of questions I will select 5 for example, then get the ID of them and get the answers to compare the right/wrong ones.

At this point I only want to import the CSV file and search for the questions...

How do I import the CSV into an array in a way that I could search for some values after importing?

I hope I detailed everything to be understandable.

Thank you.

OS:Linux

Language:PHP 5.4

  • 写回答

1条回答 默认 最新

  • doukengsha9472 2014-03-18 14:32
    关注
    $csvArray = file('file.csv');
    $base = array('Q' => array(), 'A' => array());
    foreach ($csvArray as $line) {
        $lineArray = explode(';', $line);
        //$lineArray[0] - ID
        //$lineArray[1] - text
        //$lineArray[2] - number
        //$lineArray[3] - type
        if ($lineArray[3] === 'Q') {
            $base['Q'][$lineArray[0]] = array(
                'text' => $lineArray[1],
                'number' => $lineArray[2]
            );
        } elseif ($lineArray[3] === 'A') {
            $base['A'][$lineArray[0]][] = array(
                'text' => $lineArray[1],
                'number' => $lineArray[2]
            );
        }
    }
    
    //all questions - $base['Q']
    //question item - $base['Q'][ID-question]
    //all answers for ID-question - $base['A'][ID-question]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法