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 suc开发者_高级运维h a simple question, but even after researching I just seem to be missing some basic array-logic here. Thank you!
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);
After exploding the chunks, you'll have to loop through the new array and explode the remaining strings into their own chunks.
$tempArray = array( );
foreach( $lines as $line )
{
$chunks = explode( "\n", $line );
for( $i = 1; $i < sizeof( $chunks ); $i++ )
$tempArray[$chunks[0]][] = $chunks[$i];
}
Untested PHP code, but that should work for you. $tempArray
will be the array you want.
精彩评论