具有数组结构的字符串到数组 [英] String with array structure to Array
本文介绍了具有数组结构的字符串到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有字符串:
Main.Sub.SubOfSub
还有一些数据,可能是一个字符串:
And some kind of data, may be a string:
SuperData
如何将其全部转换为上面的这个数组?
How I can transform it all to this array above?
Array
(
[Main] => Array
(
[Sub] => Array
(
[SubOfSub] => SuperData
)
)
)
感谢您的帮助,PK
推荐答案
给定值
$key = "Main.Sub.SubOfSub";
$target = array();
$value = "SuperData";
这里有一些代码可以满足您的需求¹:
Here's some code I have lying around that does what you need¹:
$path = explode('.', $key);
$root = &$target;
while(count($path) > 1) {
$branch = array_shift($path);
if (!isset($root[$branch])) {
$root[$branch] = array();
}
$root = &$root[$branch];
}
$root[$path[0]] = $value;
¹ 实际上,它的作用远不止于此:它可以简单地封装在一个函数中,并且可以在所有三个输入值上进行配置(您可以传入一个具有现有值的数组,它会根据需要对其进行扩展).
¹ Actually it does slightly more than that: it can be trivially encapsulated inside a function, and it is configurable on all three input values (you can pass in an array with existing values, and it will expand it as necessary).
这篇关于具有数组结构的字符串到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文