我有一个数组:
$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"
];
我想要得到的是将数组键分解为多维数组但保留值并且结果应该等效于此数组:
$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个(或更多)。
有没有优雅的方法来实现这个目标?
答案 0 :(得分:9)
这是我用于这样的事情:
$result = array();
foreach($array as $path => $value) {
$temp = &$result;
foreach(explode(';', $path) as $key) {
$temp =& $temp[$key];
}
$temp = $value;
}
print_r($result);
explode()
;
个键
如果您需要某些功能来执行此操作,我对 How to write getter/setter to access multi-level array by key names? 的回答可能有所帮助。
答案 1 :(得分:5)
此处的解决方案
<?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"
];
$result = [];
foreach ($array as $implodedKeys => $value) {
$keys = array_reverse(explode(';', $implodedKeys));
$tmp = $value;
foreach ($keys as $key) {
$tmp = [$key => $tmp];
}
$result = array_merge_recursive($result, $tmp);
}
var_dump($result);
一些解释: 首先迭代你给出的数组,从每一行中分解键并反转它们。现在我们可以迭代这些键并从内到外构建每个数组。最后,您可以递归地将其与结果合并。 它不是最有效的解决方案,但展示了解决问题的大量方法