从爆炸的字符串生成动态数组 [英] Generate dynamic array from exploded string
本文介绍了从爆炸的字符串生成动态数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串数组,其格式如下:
I have an array of strings that are formatted like this:
$strings = array(
"/user",
"/robot",
"/user/1",
"/user/2",
"/user/2/test",
"/robot/1"
);
我需要做的是当我<$ c $时将其转换为以下结构的数组c> print_r()它:
Array
(
[user] => Array (
[1] => array(),
[2] => Array (
[test] => array()
)
[robot] => Array (
[1] => array()
)
)
我知道我需要用定界符 /
炸开原始字符串,但是我的问题是我该如何构建动态数组。
I know I need to explode the original string by delimiter /
. However my problem is how do I then build the dynamic array.
请注意,字符串中可能有无限数量的斜杠。
Please note that the strings could potentially have an unlimited amount of slashes.
推荐答案
在遍历列表时,可以使用引用逐步构建数组。
You can use a reference to progressively build an array as you traverse through the list.
$strings = array(
"/user",
"/robot",
"/user/1",
"/user/2",
"/user/2/test",
"/robot/1"
);
$extracted = array();
foreach( $strings as $string )
{
$pos =& $extracted;
foreach( explode('/', ltrim($string, '/')) as $split )
{
if( ! isset($pos[$split]) )
{
$pos[$split] = array();
}
$pos =& $pos[$split];
}
}
print_r($extracted);
此代码可能无法很好地处理空元素(例如, / user / / 4 ////// test
),具体取决于您的要求。
This code might not handle empty elements very well (e.g., /user//4//////test
), depending on your requirements.
这篇关于从爆炸的字符串生成动态数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文