如何将平面列表转换为嵌套数组


How to turn flat list into a nested array?

我有平面数据:

$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];
  }
}

试试这个例子,尽管我看到你已经从@Marek那里得到了一个更干净的解决方案。

function recurse( &$out, $index, $values ) {
    if ( isset( $values[ $index + 1 ] ) ) {
        $out[ $values[ $index ] ] = array();
        recurse( $out[ $values[ $index ] ], $index + 1, $values );
    } else {
        $out[] = $values[ $index ];
    }
}
$out = array_map( function( $item ) {
    recurse( $temp, 0, $item );
    return $temp;
}, $flatLists );

$result = call_user_func_array( 'array_merge_recursive', $out );