假设我有这个数组:
Array
(
[0] => Array
(
[name] => ELECTRONICS
[depth] => 0
)
[1] => Array
(
[name] => TELEVISIONS
[depth] => 1
)
[2] => Array
(
[name] => TUBE
[depth] => 2
)
[3] => Array
(
[name] => LCD
[depth] => 2
)
[4] => Array
(
[name] => PLASMA
[depth] => 2
)
[5] => Array
(
[name] => PORTABLE ELECTRONICS
[depth] => 1
)
)
我想把它转换成一个多维数组,这样深度比前一个元素高的直接元素就会进入到键为"children"的前一个数组中。像这样:
Array
(
[0] => Array
(
[name] => ELECTRONICS
[depth] => 0
[children] => Array
(
[0] => Array
(
[name] => TELEVISIONS
[depth] => 1
[children] => Array
(
[0] => Array
(
[name] => TUBE
[depth] => 2
)
[1] => Array
(
[name] => LCD
[depth] => 2
)
[2] => Array
(
[name] => PLASMA
[depth] => 2
)
)
)
[1] => Array
(
[name] => PORTABLE ELECTRONICS
[depth] => 1
)
)
)
)
非常感谢您的帮助。谢谢;)
这是我的破解方法…使用foreach循环和指针数组来跟踪一堆不同的父指针。
$multi_dimensional = array();
$last_depth = 0;
$parent = &$multi_dimensional;
$parents[$last_depth] = &$parent;
foreach ($start as $idx => $data) {
// same/increasing depth
if ($last_depth <= $data['depth']) {
$parent['children'][] = $data;
}
// increasing depth
if ($last_depth < $data['depth']) {
$parents[$last_depth] = &$parent;
}
// decreasing depth
if ($last_depth > $data['depth']) {
$parent = &$parents[$data['depth']-1];
$parent['children'][] = $data;
}
// look ahead and prepare parent in increasing
if (isset($start[$idx+1]) && $start[$idx+1]['depth'] > $data['depth']) {
$last_insert_idx = count($parent['children'])-1;
$parent = &$parent['children'][$last_insert_idx];
}
$last_depth = $data['depth'];
}
// initial values are in child "children" array
$result = $multi_dimensional['children'];
这是一个棘手的问题。我不确定这是否是实现这一目标的最佳方式,但它确实有效:
function flat_to_tree($array, $depth = 0)
{
$out = array();
$inCurrentDepth = true;
foreach ($array as $key => $value) {
if ($value['depth'] < $depth) {
return $out;
}
if ($value['depth'] === $depth) {
$inCurrentDepth = true;
$out[] = $value;
}
if ($inCurrentDepth && $value['depth'] > $depth) {
$inCurrentDepth = false;
$out[$key - 1]['children'] = flat_to_tree(array_slice($array, $key), $value['depth']);
}
}
return $out;
}
我为它的名称和递归性质道歉。此外,请注意,这个函数会"破坏"您的原始数组,所以如果您想保持,请使用克隆
function multiDimensionate(&$arr, $currentLevel = 0) {
$root = array();
foreach ($arr as &$elem){
if ($elem["depth"] == $currentLevel) {
$root[] = $elem;
unset($elem);
} else if ($elem["depth"] == $currentLevel + 1) {
$root[count($root)-1]["children"] = multiDimensionate($arr,$elem["depth"]);
}
}
return $root;
}
编辑:正如coments中所指出的,以前的函数没有正常工作,这应该没问题,仍然有破坏原始数组的副作用。