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
總結
以上是生活随笔為你收集整理的php递归多维数组为缩进列表,php – 缩进列表到多维数组的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c#截取字符串指定符号,在.NET中,C
- 下一篇: 超小型php框架,MiniFramewo