我在这样的多维数组中有一个数据树:
[0] => Array
(
[0] => 14
[1] => 12
[2] => Array
(
[0] => Array
(
[0] => 16
[1] => 13
)
[1] => Array
(
[0] => 13
)
[2] => Array
(
[0] => 16
)
)
)
[1] => Array
(
[0] => 12
)
...我正在尝试编写一个输出此算法的算法:
[0] => Array
(
[0] => 14
[1] => 12
[2] => 16
[3] => 13
)
[1] => Array
(
[0] => 14
[1] => 12
[0] => 13
)
[2] => Array
(
[0] => 14
[1] => 12
[0] => 16
)
[3] => Array
(
[0] => 12
)
我可以提出的最佳方法是递归数组合并,它显示通过给定数组树的所有路径的所有可能的合并数组排列。
我最接近的是:
[0] => Array
(
[0] => 14
[1] => 12
[2] => 16
[3] => 13
)
[1] => Array
(
[0] => 13
)
[2] => Array
(
[0] => 16
)
[3] => Array
(
[0] => 12
)
输出的代码是:
$return = [];
function enumerateTreePaths($arr, &$return, $path_k = 0)
{
foreach ($arr as $el)
{
if (is_array($el))
{
foreach($el as $i)
{
enumerateTreePaths($i, $return, $path_k++);
}
}
else
{
$return[$path_k][] = $el;
}
}
}
为粗心的命名约定道歉。递归==大脑融化。
我显然需要在那里进行某种数组合并,但未能找到精确的逻辑。
感谢您的任何意见。
哦,这实际上也包含在foreach中;
foreach ($trees as $tree)
{
$return = [];
enumerateTreePaths($tree, $return);
$paths = array_merge($paths, $return);
}