PHP将字符串键分解为带有值的多维数组 [英] PHP explode string key into multidimensional array with values
本文介绍了PHP将字符串键分解为带有值的多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数组:
$array = [
"main;header;up" => "main_header_up value",
"main;header;bottom" => "main_header_bottom value",
"main;bottom" => "main_bottom value",
"main;footer;right;top" => "main_footer_right_top value"
];
我想要得到的是将数组键分解为多维数组,但保留值,结果应等于此数组:
What I'd like to get is explode the array keys into multidimensional array but keep the values and the result should be equivalent of this array:
$array = [
"main" => [
"header" => [
"up" => "main_header_up value",
"bottom" => "main_header_bottom value"
],
"bottom" => ["main_bottom value"],
"footer" => [
"right" => [
"top" => "main_footer_right_top value
]
]
]
];
我想我应该声明;
的数量不是预先确定的.键/索引中可能没有,或者可能有10个(或更多).
I guess I should state that the number of ;
is not predetermined. There could be none or there could be 10 (or more) of them in a key / index.
有什么优雅的方法可以做到这一点吗?
Is there any elegant way to achieve this?
推荐答案
在这里,我使用的是这样的东西:
Here is what I use for things like this:
$result = array();
foreach($array as $path => $value) {
$temp =& $result;
foreach(explode(';', $path) as $key) {
$temp =& $temp[$key];
}
$temp = $value;
}
print_r($result);
查看全文