0

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

9
  • What OS (e.g. Windows, Linux, ...), RDBMS (e.g. Sqlite, Oracle, MS-SQL Server) and, maybe, language (e.g. C, bash, Python, Tcl, Perl) do you want to do this in? That kinda affects the answer :) Commented Mar 16, 2014 at 23:12
  • Oh sorry. No MySQL in this only PHP and the server is running in Linux. Commented Mar 16, 2014 at 23:15
  • Have you tried MySQL's LOAD DATA INFILE? Is this post any help? Commented Mar 16, 2014 at 23:21
  • You have outlined a task to be completed, but failed to ask a question. Could you rephrase, such that a suitable question is being asked? Commented Mar 16, 2014 at 23:24
  • Once again, I'm sorry, post edited. Question: How do I import the CSV into an array in a way that I could search for some values after importing? Commented Mar 16, 2014 at 23:26

1 Answer 1

1
$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]
Sign up to request clarification or add additional context in comments.

2 Comments

The array have all the data. I will continue developing and leave here the complete code.
How can I print all the questions? I tried echoing $base['Q'] but it appear only array...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.