从分解的字符串生成动态数组
我有一个格式如下的字符串数组:
$strings = array(
"/user",
"/robot",
"/user/1",
"/user/2",
"/user/2/test",
"/robot/1"
);
我需要做的就是当我 print_r()
时将其转换为以下结构的数组:
Array
(
[user] => Array (
[1] => array(),
[2] => Array (
[test] => array()
)
[robot] => Array (
[1] => array()
)
)
我知道我需要分解原始字符串通过分隔符/
。然而我的问题是如何构建动态数组。
请注意,字符串可能有无限数量的斜杠。
I have an array of strings that are formatted like this:
$strings = array(
"/user",
"/robot",
"/user/1",
"/user/2",
"/user/2/test",
"/robot/1"
);
What I need to do is turn this into an array of the following structure when I print_r()
it:
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在遍历列表时使用引用逐步构建数组。
此代码可能无法很好地处理空元素(例如,
/user//4//////test
),具体取决于您的要求。You can use a reference to progressively build an array as you traverse through the list.
This code might not handle empty elements very well (e.g.,
/user//4//////test
), depending on your requirements.以下代码应该为您提供您要查找的或非常接近的内容...
初始化数组,然后循环所有字符串并将它们分解在 / 上(删除第一个字符串)。然后,设置对结果数组第一级的初始引用。注意&,在这个算法中继续下去是至关重要的。
然后,循环分解的字符串的每个部分,检查该部分是否作为键存在于当前 $path 中,该 $path 链接到我们所在结果中的当前步骤。在每个循环中,我们创建丢失的键并将其初始化为 array(),然后使用该新数组并使用引用将其保存为新的 $path...
祝其余的好运
The following piece of code should give you what you look for or very near...
Initialize the array and then loop all strings and exploded them on the / (removing the first one). Then, setup an initial reference to the first level of the results array. Notice the &, it is critical in this algorithm to keep going.
Then, looping each part of the string that you exploded, you check if the part exists as a key inside the current $path which is linked to the current step in results we are at. On each loop, we create the missing key and initialize it to array() and then take that new array and save it as the new $path using a reference...
Good luck with the rest