0

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.

3
  • 1
    Solution please!! it's not working like that. First, show us what have you tried so far. Commented Sep 13, 2015 at 1:16
  • Wheres the code? If you have use the file() function Commented Sep 13, 2015 at 1:19
  • I read a txt file named "text.txt" using php read function. I used foreach to loop through each line, I explode each line by space, to differentiate between header and list items that followed. Now, I needed a solution to form array shown above. Commented Sep 13, 2015 at 1:22

1 Answer 1

1

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
     )
)
Sign up to request clarification or add additional context in comments.

2 Comments

I'm new here, I tried to vote but I could not. It solves my problems. Thanks, you're the best @rizier123
@Lian You're welcome. Have a nice day :) (If you are new here, you can take a quick tour: stackoverflow.com/tour to get an overview of this site)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.