缩进列表到多维数组 [英] Indented list to multidimensional array

查看:84
本文介绍了缩进列表到多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was surprised not to find an answer to this on SO (or elsewhere on the internet for that matter). It concerns a nested indented list which I want to convert into a multidimensional array according to the level of indentation.

通过示例,下面是一些示例输入:

By way of an example, here is some sample input:

Home
Products
    Product 1
        Product 1 Images
    Product 2
        Product 2 Images
    Where to Buy
About Us
    Meet the Team
    Careers
Contact Us

理想情况下,我想将此输入到某些(递归?)函数中并获得以下输出:

Ideally I'd like to feed this into some (recursive?) function and get the following output:

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(),
);

我对执行此类任务所需的逻辑感到困惑,因此将不胜感激.

I'm confused by the logic required to perform such a task, so any help would be appreciated.

推荐答案

由于尚不清楚您是尝试从给定结构(html-dom)还是给定字符串中读取纯文本,因此我认为这是您要解析的字符串.如果是这样,请尝试:

As it's still unclear if you're trying to read from some given structure (html-dom) or from the given string as plain text, I assumed it's the string you're trying to parse. If so, try:

<?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));

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

这篇关于缩进列表到多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆