字符串数组结构数组 [英] String with array structure to Array
本文介绍了字符串数组结构数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的字符串:
Main.Sub.SubOfSub
和某些类型的数据,可能是一个字符串:
And some kind of data, may be a string:
SuperData
另外我有一个空数组:
Also I have an empty array:
$k = array();
我怎样可以把它全部转换到这个阵列上方?
How I can transform it all to this array above?
Array
(
[Main] => Array
(
[Sub] => Array
(
[SubOfSub] => SuperData
)
)
)
感谢您的帮助, PK
Thanks for help, PK
推荐答案
给出的值
$key = "Main.Sub.SubOfSub";
$target = array();
$value = "SuperData";
下面是一些code我已经躺在附近,它是你need¹:
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;
See it in action.
¹实际上它确实比略多:可以平凡封装在一个函数中,它是在所有三个输入值配置的(你可以通过在现有值的数组,它会根据需要进行扩展)。
¹ 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屋!
查看全文