缩进列表到多维数组

Sam*_*ngs 2 php

我很惊讶没有在SO(或互联网上的其他地方)找到答案.它涉及一个嵌套的缩进列表,我想根据缩进的级别将其转换为多维数组.

举个例子,这里有一些示例输入:

Home
Products
    Product 1
        Product 1 Images
    Product 2
        Product 2 Images
    Where to Buy
About Us
    Meet the Team
    Careers
Contact Us
Run Code Online (Sandbox Code Playgroud)

理想情况下,我想将其提供给一些(递归?)函数并获得以下输出:

array(
    'Home' => array(),
    'Products' => array(
        'Product 1' => array(
            'Product 1 Images' => array(),
        ),
        'Product 2' => array(
            'Product 2 Images' => array(),
        ),
        'Where to Buy' => array(),
    ),
    'About Us' => array(
        'Meet the Team' => array(),
        'Careers' => array(),
    ),
    'Contact Us' => array(),
);
Run Code Online (Sandbox Code Playgroud)

我对执行这样一项任务所需的逻辑感到困惑,所以任何帮助都会受到赞赏.

Yos*_*shi 11

由于目前还不清楚你是想尝试从一些给定的结构(html-dom)或从给定的字符串中读取纯文本,我认为它是你试图解析的字符串.如果是这样,请尝试:

<?php
$list =
'Home
Products
    Product 1
        Product 1 Images
    Product 2
        Product 2 Images
    Where to Buy
About Us
    Meet the Team
    Careers
Contact Us';

function helper($list, $indentation = '    ') {
  $result = array();
  $path = array();

  foreach (explode("\n", $list) as $line) {
    // get depth and label
    $depth = 0;
    while (substr($line, 0, strlen($indentation)) === $indentation) {
      $depth += 1;
      $line = substr($line, strlen($indentation));
    }

    // truncate path if needed
    while ($depth < sizeof($path)) {
      array_pop($path);
    }

    // keep label (at depth)
    $path[$depth] = $line;

    // traverse path and add label to result
    $parent =& $result;
    foreach ($path as $depth => $key) {
      if (!isset($parent[$key])) {
        $parent[$line] = array();
        break;
      }

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

  // return
  return $result;
}

print_r(helper($list));
Run Code Online (Sandbox Code Playgroud)

演示:http://codepad.org/zgfHvkBV