php递归多维数组为缩进列表,php – 缩进列表到多维数组

标签: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

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

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

);

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

解决方法:

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

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

标签:php

来源: https://codeday.me/bug/20190927/1823419.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值