Create Multidimensional array from text lines

2019-09-12 05:14发布

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.

1条回答
来,给爷笑一个
2楼-- · 2019-09-12 05:35

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

查看更多
登录 后发表回答