日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > php >内容正文

php

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

發布時間:2024/4/18 php 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 – 缩进列表到多维数组的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。