Jen*_*ell 20 php arrays recursion loops parent-child
我在Idiorm中使用PHP和mySQL .这可能不相关.
我的PHP数组
如果需要解决问题,可以更改此阵列结构.
array (
33 =>
array (
0 => '27',
1 => '41',
),
27 =>
array (
0 => '64',
1 => '71',
),
0 =>
array (
0 => '28',
1 => '29',
2 => '33',
),
)
Run Code Online (Sandbox Code Playgroud)
我的分层结果
像这样的东西,但作为一个数组......
0 =>
28
29
33
27 =>
64
71
41
Run Code Online (Sandbox Code Playgroud)
信息
我自己的想法
我尝试了上述两种情况,只是搞得一团糟.这是一个脑子.
Jen*_*ell 51
@deceze的建议奏效了.但是输入数组需要改变litte,就像这样......
$rows = array(
array(
'id' => 33,
'parent_id' => 0,
),
array(
'id' => 34,
'parent_id' => 0,
),
array(
'id' => 27,
'parent_id' => 33,
),
array(
'id' => 17,
'parent_id' => 27,
),
);
Run Code Online (Sandbox Code Playgroud)
function buildTree(array $elements, $parentId = 0) {
$branch = array();
foreach ($elements as $element) {
if ($element['parent_id'] == $parentId) {
$children = buildTree($elements, $element['id']);
if ($children) {
$element['children'] = $children;
}
$branch[] = $element;
}
}
return $branch;
}
$tree = buildTree($rows);
print_r( $tree );
Run Code Online (Sandbox Code Playgroud)
我添加了@JensTörnell的答案,以便为parent_id的列名,子数组键名以及id的列名定义选项.
/**
* function buildTree
* @param array $elements
* @param array $options['parent_id_column_name', 'children_key_name', 'id_column_name']
* @param int $parentId
* @return array
*/
function buildTree(array $elements, $options = [
'parent_id_column_name' => 'parent_id',
'children_key_name' => 'children',
'id_column_name' => 'id'], $parentId = 0)
{
$branch = array();
foreach ($elements as $element) {
if ($element[$options['parent_id_column_name']] == $parentId) {
$children = buildTree($elements, $options, $element[$options['id_column_name']]);
if ($children) {
$element[$options['children_key_name']] = $children;
}
$branch[] = $element;
}
}
return $branch;
}
Run Code Online (Sandbox Code Playgroud)
由于功能非常普遍,我设法在大多数项目中使用上述功能.