1 回答
TA贡献1794条经验 获得超8个赞
伟大的尝试,而且非常在正确的轨道上。比较器中递归的问题在于,usort当数组长度为 1 时不会调用比较器函数,因此是否探索整棵树是usort. 这将放弃id => 245982树的分支。
解决方案是避免usort直接在的比较器函数中递归。相反,使用usort根据需要调用的常规递归函数,即当前数组或子数组包含目标 id。我使用一个单独的数组来跟踪哪些元素应该向前移动,但是如果您愿意,您可以跳出循环并将单个元素拼接/取消移动到前面。
我们还可以为$category_id函数设置一个参数。
这是一种方法:
function reorder_tree_r(&$children, $target) {
$order = [];
$should_sort = false;
foreach ($children as $i => &$child) {
$order[$i] = false;
if (array_key_exists("children", $child) &&
reorder_tree_r($child["children"], $target) ||
$child["id"] === $target) {
$order[$i] = true;
$should_sort = true;
}
}
if ($should_sort) {
$priority = [];
$non_priority = [];
for ($i = 0; $i < count($children); $i++) {
if ($order[$i]) {
$priority[]= $children[$i];
}
else {
$non_priority[]= $children[$i];
}
}
$children = array_merge($priority, $non_priority);
}
return $should_sort;
}
function reorder_tree($tree, $target) {
if (!$tree || !array_key_exists("children", $tree)) {
return $tree;
}
reorder_tree_r($tree["children"], $target);
return $tree;
}
var_export(reorder_tree($tree, 225902));
输出:
array (
'id' => 245974,
'children' =>
array (
0 =>
array (
'id' => 245982,
'children' =>
array (
0 =>
array (
'id' => 246093,
'children' =>
array (
0 =>
array (
'id' => 225902,
),
1 =>
array (
'id' => 225892,
),
2 =>
array (
'id' => 225893,
),
),
),
),
),
1 =>
array (
'id' => 111,
),
),
- 1 回答
- 0 关注
- 126 浏览
添加回答
举报