Fred Cardoso
Fred Cardoso

Reputation: 323

Parse CSV into array and search for values inside that array

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

Upvotes: 0

Views: 828

Answers (1)

Sergey Krivov
Sergey Krivov

Reputation: 372

$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]

Upvotes: 1

Related Questions