use*_*217 5 php arrays sorting algorithm multidimensional-array
我正在使用PHP,我需要一个看似简单的数组任务的帮助.
这是我的示例数组:
$arr = array(
0 => NULL,
1 => NULL,
2 => NULL,
3 => NULL,
8 => '2',
9 => '2',
10 => '2',
11 => '2',
12 => '3',
13 => '3',
14 => '8',
15 => '8',
16 => '14',
17 => '14',
18 => '14'
);
Run Code Online (Sandbox Code Playgroud)
数组的键表示ID(唯一).
值是parentID,即父"节点"的ID.NULL表示没有parentID(即新数组的第一维).
现在,我需要创建一个新的多维数组,其父元素下包含所有子元素.(这可能听起来很混乱,抱歉我缺乏描述性能力.下面有一个例子,应该让事情更清楚)
以下是我的示例的新数组在"排序"函数或者您调用此函数之后的应用:
$arr = array(
0 => array(),
1 => array(),
2 => array(
8 => array(
14 => array(
16 => array(),
17 => array(),
18 => array()
),
15 => array()
),
9 => array(),
10 => array(),
11 => array()
),
3 => array(
12 => array(),
13 => array()
)
);
我知道所有空数组()都可能不是一个非常干净和优雅的解决方案,但遗憾的是这就是我需要它的方式!
此递归函数会将给定的数据添加到正确的父级,并且应该为起始数组中的每个元素调用一次。
function add_branch(&$tree, $datum, $parent) {
// First we have the base cases:
// If the parent is NULL then we don't need to look for the parent
if ($parent == NULL) {
$tree[$datum] = array();
return true;
}
// If the array we've been given is empty, we return false, no parent found in this branch
if (! count($tree)) {
return false;
}
// We loop through each element at this level of the tree...
foreach($tree as $key => $val) {
// If we find the parent datum...
if ($key == $parent) {
// We add the new array in and we're done.
$tree[$key][$datum] = array();
return true;
}
// Otherwise, check all the child arrays
else {
// Now we check to see if the parent can be found in the curent branch
// If a recursive call found a parent, we're done
if (add_branch($tree[$key], $datum, $parent)) {
return true;
}
}
}
// If none of the recursive calls found the parent, there's no match in this branch
return false;
}
Run Code Online (Sandbox Code Playgroud)
评论相当冗长,希望您能明白发生了什么。我鼓励您阅读一些有关递归函数的内容,以了解它。
这是它的使用方式:
$arr = array(
0 => NULL,
1 => NULL,
2 => NULL,
3 => NULL,
8 => '2',
9 => '2',
10 => '2',
11 => '2',
12 => '3',
13 => '3',
14 => '8',
15 => '8',
16 => '14',
17 => '14',
18 => '14'
);
$final = array();
foreach ($arr as $datum => $parent) {
add_branch($final, $datum, $parent);
}
Run Code Online (Sandbox Code Playgroud)
$final现在有了正确的整理数组,如问题所示。