Search code examples
phparraysmultidimensional-arraytext-filesflat-file

Explode several newlines into multidimensional array with php


I have a .txt document set up like this:

HAYLE08
VALUE X
VALUE Y

BRUNO10
VALUE X
VALUE Y

Which needs to processed to a multidimensional array like this:

Array
(
    [HAYLE08] => Array
        (
            [0] => Value X
            [1] => Value Y
        )

    [BRUNO10] => Array
        (
            [0] => Value X
            [1] => Value Y
        )

)

Reading the file into php is no problem and exploding the different chunks of 3-lines is very easy like this:

$file = file_get_contents('test.txt'); 
$lines = explode( "\n\n", $file );

But of course, this will only give me the first step:

Array
(
    [0] => HAYLE08
VALUE X
VALUE Y
    [1] => BRUNO10
VALUE X
VALUE Y

)

I've tried different foreaches and other loops or line explodes to populate the other dimensions, yet all in vain. I feel kind of stupid to ask such a simple question, but even after researching I just seem to be missing some basic array-logic here. Thank you!


Solution

  • Your almost there. You do want to use another loop / explode. Something like this:

    $lines = explode( "\n\n", $file );
    $return = array();
    
    foreach ($lines as $line) {
      $items = explode("\n", $line);
      $return[array_shift($items)] = $items;
    }
    
    print_r($return);