Php 如何将平面列表转换为嵌套数组?
我有平面数据:Php 如何将平面列表转换为嵌套数组?,php,arrays,sorting,multidimensional-array,tree,Php,Arrays,Sorting,Multidimensional Array,Tree,我有平面数据: $flatLists = [ [ 'task', 'updater', 'updater_xml', 'some_customer', 'some_customer_de', ], [ 'task', 'updater', 'updater_xml', 'some_customer', 'some
$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获得了一个clener解决方案
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 );
在平面列表中,每个条目总是有4/5个元素吗?或者可以是任意数量的元素?@MariM理论上,条目的数量可能是无限的。叶子是值而不是键吗?@Marek我真的不介意它们是如何存储的。最后一个键既可以是值也可以是键,最后我认为树结构是保持不变的。