问题描述:

I tried to write a php code that would read a text file, convert it into a multidimensional array.

My text looks like:

Random Header 1

1. List item 1

2. List item 2

3. List item 3

...........

...........

Random Header Title 2

1. List item 1

2. List item 2

3. List item 3

...........

...........

and the random header and lists

And now, I want to convert the above text into array that looks,

Array

(

[Random Header 1] => Array

(

[0] => "1. List item 1",

[1] => "2. List item 2",

[2] => "3. List item 3"

),

[Random Header Title 2] => Array

(

[0] => "1. List item 1",

[1] => "2. List item 2",

[2] => "3. List item 3"

)

)

Notice that the headers begins with a string, and list items start with number.

I used php's file() function to read, I have a hard time converting into the way I wanted.

网友答案:

This should work for you:

Just use file() as you already did and loop through each line and check with preg_match() if the first character of the line is a non-digit character (\D -> [^0-9]). If yes use it as key until you hit the next line with a non-digit character at the start.

<?php

    $lines = file("text.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $arr = [];
    $header = FALSE;

    foreach($lines as $line){
        if(preg_match("/^\D/", $line))
            $header = $line;
        if($header != $line)
            $arr[$header][] = $line;
    }

    print_r($arr);

?>

output:

Array
(
    [Random Header 1] => Array
        (
           [0] => 1. List item 1
           [1] => 2. List item 2
           [2] => 3. List item 3
     )
     [Random Header Title 2] => Array
        (
           [0] => 1. List item 1
           [1] => 2. List item 2
           [2] => 3. List item 3
     )
)
相关阅读:
Top