我有一个数组,我们称之为 $childrenIds,它的输出如下:
array(
[74252] => Array
(
[0] => 1753
[1] => 1757
[2] => 1758
[3] => 1760
)
[74238] => Array
(
[0] => 1753
[1] => 1755
[2] => 1758
[3] => 1761
)
[76476] => Array
(
[0] => 1754
[1] => 1755
[2] => 1758
[3] => 1763
)
[76478] => Array
(
[0] => 1754
[1] => 1756
[2] => 1758
[3] => 1763
)
[76480] => Array
(
[0] => 1754
[1] => 1757
[2] => 1758
[3] => 1763
)
[74253] => Array
(
[0] => 1753
[1] => 1757
[2] => 1759
[3] => 1760
)
); 我需要做的是从中创建一个新数组,其中例如 [74252] 被忽略,但每个子数组的子数组都被路径...
因此,使用此示例,我的输出将类似于:array(
[1753] => Array
(
[1757] => Array
(
[1758] => Array
(
1760
),
[1759] => Array
(
1760
),
)
[1755] => Array
(
1758 => Array
(
1761
)
)
)
),
[1754] => Array
(
[1755] => Array
(
[1758] => Array
(
1763
)
),
[1756] => Array
(
[1758] => Array
(
1763
)
),
[1757] => Array
(
[1758] => Array
(
1763
)
)
)
);
所以不会总是有4个子数组元素,那是动态的......
父母只是基于该数组的索引。所以... index[0] 是 index[1] 的父级, index[1] 是 index[2] 的父级,依此类推。
另外,我想以所有唯一路径结束,每个路径没有重复值。
希望我已经清楚地解释了这一点,一直在寻找几个小时,但找不到满足我所有要求的解决方案,如果我忽略了一个,我提前道歉。
谢谢
更新
与传递数组相反,我最终传递了一个下划线分隔的字符串,然后使用此函数:
function explodeTree($array, $delim = '/')
{
$tree = array();
foreach($array as $elem)
{
// Split our string up, and remove any blank items
$items = explode($delim, $elem);
$items = array_diff($items, array(''));
// current holds the current position in the tree
$current = &$tree;
foreach($items as $item)
{
// If we've not created this branch before, or there is
// a leaf with the same name, then turn it into a branch
if(!isset($current[$item]) || !is_array($current[$item]))
{
$current[$item] = array();
}
// Update our current position to the branch we entered
// (or created, depending on the above if statement)
$current = &$current[$item];
}
// If the last value in this row is an array with 0 elements
// then (for now) we will consider it a leaf node, and set it
// to be equal to the string representation that got us here.
if(count($current) == 0)
{
$current = $elem;
}
}
return $tree;
}
找到@:
http
://project-2501.net/index.php/2007/10/explodetree/
和:http:
//kevin.vanzonneveld.net/techblog/article/convert_anything_to_tree_structures_in_php/
我能够获得预期的结果。