Search code examples
phparraysmultidimensional-arraytext-filesnotepad

read .txt file content into php multi dimensional array


I have a .txt file with content like this

  1. Abuja, the Federal Capital Territory has -- -- -- -- -- area Council
    A. 4
    B. 6
    C. 7
    D. 2
    ANSWER: B

  2. The Federal Capital Territory is associated with-- -- -- -- -- -- -- vegetation belt
    A. Sahel savanna
    B. Rainforest
    C. Guinea savanna
    D. Sudan savanna
    ANSWER: C

  3. The most significant factor responsible for the ever increasing population of FCT is
    A. High birth rate
    B. Immigration
    C. Death rate
    D. CENSUS
    ANSWER: B

i would love to read the file content into a multi dimensional array so i can get each questions, its answers and the correct answer for each of the questions.

i have tried this:-

$array=explode("\n", file_get_contents('file.txt')); 
print_r($array);

but it doesn't give me what i want..


Solution

  • Alives answer gives a result that you probably can work with, but I think associative array is probably the way to go.

    I look at each line to see if it has a question number => add new item in array with question number and question text.

    If first char is letter and second is a dot, it's an answer => add answer letter as key and text as value.

    If it's none of above it's the answer text => add key with ANSWER and value as the correct answer.

    I use explode to split the lines. The third argument tells how many parts to split the string in.
    With "2" it splits at first space meaning I have the question# as item 1 and question text as item 2 in the array.

    https://3v4l.org/ZqppN

    // $str = file_get_contents("text.txt");
    $str = "1. Abuja, the Federal Capital Territory has -- -- -- -- -- area Council
    A. 4
    B. 6
    C. 7
    D. 2
    ANSWER: B
    
    2. The Federal Capital Territory is associated with-- -- -- -- -- -- -- vegetation belt
    A. Sahel savanna
    B. Rainforest
    C. Guinea savanna
    D. Sudan savanna
    ANSWER: C
    
    3. The most significant factor responsible for the ever increasing population of FCT is
    A. High birth rate
    B. Immigration
    C. Death rate
    D. CENSUS
    ANSWER: B";
    
    $arr = explode("\n", $str);
    
    $res=[];
    
    Foreach($arr as $line){
        If($line != ""){
            If(is_numeric($line[0])){
                Preg_match("/^\d+/", $line, $num);
                $res[$num[0]] =["QUESTION" =>explode(" ", $line,2)[1]];
                $q = $num[0];
            }Else if(ctype_alpha($line[0]) && $line[1] == "."){
                $res[$q][$line[0]] = explode(" ", $line, 2)[1];
            }Else{
                $res[$q]["ANSWER"] = trim(explode(":", $line, 2)[1]);
            }
        }
    }
    
    Var_dump($res);