我有平面数据:
$flatLists = [
[
'task',
'updater',
'updater_xml',
'some_customer',
'some_customer_de',
],
[
'task',
'updater',
'updater_xml',
'some_customer',
'some_customer_fr',
],
[
'task',
'updater',
'updater_json',
'yet_another_customer',
'yet_another_customer_us',
],
[
'task',
'updater',
'updater_json',
'updater_flatfile',
],
];
它代表一个继承结构,第一个元素是第一个父元素,每个条目都是一个子元素。
我现在想要将这个平面数组转换为嵌套数组,以便结果看起来像:
$expectedArray = [
'task' => [
'updater' => [
'updater_xml' => [
'some_customer' => [
'some_customer_de',
'some_customer_fr',
],
],
'updater_json' => [
'yet_another_customer' => [
'yet_another_customer_us',
],
'updater_flatfile',
],
],
],
];
我尝试通过 foreach
、for
以多种方式迭代平面列表,但没有任何方法可以正常工作,现在我的大脑很痛。
我不期望有一个有效的代码示例,但我希望得到一些有关如何解决此问题的提示,并希望我可以发布自己的答案。现在,我陷入困境。
最佳答案
与您的$expectedArray
不同,这会创建结构,其中叶子是键,空数组作为值:
$result = [];
foreach($flatLists as $list) {
$target = &$result;
foreach($list as $element) {
if(!isset($target[$element])) {
$target[$element] = [];
}
$target = &$target[$element];
}
}
关于php - 如何将平面列表变成嵌套数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31459630/