0

If you have a text file like this:

item1
item1 > item3
item1 > item3 > item4
item1 > item5
item1 > item5 > item6 > item7
item2 > item8
item2 > item8 > item9

And I want a array that looks like this:

array(
        [item1]
                array(
                        [item3]
                                array(
                                        [item4]
                                )
                        [item5]
                                array(
                                        [item6]
                                                array(
                                                        [item7]
                                                )
                                )
                )
        [item2]
                array(
                        [item8]
                                array(
                                        [item9]
                                )              
                )
    )

How should I make this in PHP? I have no idea where to start. Thanks.

2
  • is that a sigle string or different strings? Commented Feb 1, 2013 at 9:03
  • what should be the value for each, you just mentioned then as keys Commented Feb 1, 2013 at 9:05

1 Answer 1

3

Here's a very simple way to approach your problem. The result is not exactly the same (the last element is also an array) but this is more flexible I think:

$input = array(
  'item1',
  'item1 > item3',
  'item1 > item3 > item4',
  'item1 > item5',
  'item1 > item5 > item6 > item7',
  'item2 > item8',
  'item2 > item8 > item9',
);

$data = array();
foreach ($input as $line) {
  $parent =& $data;  
  foreach (array_map('trim', explode('>', $line)) as $el) {
    if (!isset($parent[$el])) {
      $parent[$el] = array();
    }

    $parent =& $parent[$el];
  }
}

print_r($data);

/*
Array (
  [item1] => Array (
    [item3] => Array (
      [item4] => Array ()
    )
    [item5] => Array (
      [item6] => Array (
        [item7] => Array ()
      )
    )
  )
  [item2] => Array (
    [item8] => Array (
       [item9] => Array ()
    )
  )
)
*/

demo: http://codepad.viper-7.com/IwZFQ3

Sign up to request clarification or add additional context in comments.

Comments

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.